導航:首頁 > 編程語言 > javamail設置pop3

javamail設置pop3

發布時間:2024-11-10 19:52:41

java收發郵件過程中具體的功能是怎麼實現的

qq郵箱為例:


packagemain;

importjava.util.Properties;

importjavax.mail.Authenticator;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMessage.RecipientType;


publicclassSendMessageService{
;
privateMimeMessagemessage;
privatePropertiesprops=newProperties();
publicstaticStringuserName;
publicstaticStringpassword;
;
;

SendMessageService(){
{
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host","smtp.qq.com");
props.put("mail.smtp.port","587");
props.put("mail.user","[email protected]");//發送出去郵箱,
props.put("mail.password","在騰訊郵箱申請的SMTP服務碼");

//用戶名、密碼
userName=props.getProperty("mail.user");
password=props.getProperty("mail.password");

//構建授權信息,用於進行SMTP進行身份驗證
Authenticatorauthenticator=newAuthenticator(){
(){
(userName,password);
}
};
mailSession=Session.getInstance(props,authenticator);
message=newMimeMessage(mailSession);
InternetAddressform=newInternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
}catch(MessagingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}

}

/**參數,發送的郵件的標題,郵件的內容,目標郵箱地址**/
publicvoidsendEm(Stringstr,Stringcont,Stringmailbox){
try{
//添加目標郵箱地址
to=newInternetAddress(mailbox);
message.setRecipient(RecipientType.TO,to);
//設置郵件標題
message.setSubject(str);
//設置郵件的內容體
message.setContent(cont,"text/html;charset=UTF-8");
Transport.send(message);
}catch(MessagingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
newSendMessageService().sendEm("hahhahahhaha","哈哈哈哈哈哈","[email protected]");
}
}

申請/SMTP服務 ,先進入郵箱,點擊設置,賬戶設置,翻到下面的開啟第二個IMAP/SMTP服務 ,會得到一個SMTP碼,記住它,

㈡ javamail收發信件時,伺服器,收發方的名稱應該怎樣設置才有效呢

package com.gwxc.hz.mail.demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class ReciveOneMail {

/**
* 有一封郵件就需要建立一個ReciveMail對象
*/
private MimeMessage mimeMessage = null;
private String saveAttachPath = ""; // 附件下載後的存放目錄
private StringBuffer bodytext = new StringBuffer();// 存放郵件內容
private String dateformat = "yy-MM-dd HH:mm"; // 默認的日前顯示格式

public ReciveOneMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

public void setMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

/**
* 獲得發件人的地址和姓名
*/
public String getFrom() throws Exception {
InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
String from = address[0].getAddress();
if (from == null)
from = "";
String personal = address[0].getPersonal();
if (personal == null)
personal = "";
String fromaddr = personal + "<" + from + ">";
return fromaddr;
}

/**
* 獲得郵件的收件人,抄送,和密送的地址和姓名,根據所傳遞的參數的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
*/
public String getMailAddress(String type) throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")
|| addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email);
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal + "<" + email + ">";
mailaddr += "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}

/**
* 獲得郵件主題
*/
public String getSubject() throws MessagingException {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {
}
return subject;
}

/**
* 獲得郵件發送日期
*/
public String getSentDate() throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}

/**
* 獲得郵件正文內容
*/
public String getBodyText() {
return bodytext.toString();
}

/**
* 解析郵件,把得到的郵件內容保存到一個StringBuffer對象中,解析郵件 主要是根據MimeType類型的不同執行不同的操作,一步一步的解析
*/
public void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
System.out.println("CONTENTTYPE: " + contenttype);
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
} else {
}
}

/**
* 判斷此郵件是否需要回執,如果需要回執返回"true",否則返回"false"
*/
public boolean getReplySign() throws MessagingException {
boolean replysign = false;
String needreply[] = mimeMessage
.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}

/**
* 獲得此郵件的Message-ID
*/
public String getMessageId() throws MessagingException {
return mimeMessage.getMessageID();
}

/**
* 【判斷此郵件是否已讀,如果未讀返回返回false,反之返回true】
*/
public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = ((Message) mimeMessage).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
System.out.println("flags's length: " + flag.length);
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
System.out.println("seen Message.......");
break;
}
}
return isnew;
}

/**
* 判斷此郵件是否包含附件
*/
public boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false;
String contentType = part.getContentType();
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE))))
attachflag = true;
else if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach((Part) mpart);
} else {
String contype = mpart.getContentType();
if (contype.toLowerCase().indexOf("application") != -1)
attachflag = true;
if (contype.toLowerCase().indexOf("name") != -1)
attachflag = true;
}
}
} else if (part.isMimeType("message/rfc822")) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}

/**
* 【保存附件】
*/
public void saveAttachMent(Part part) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
}

/**
* 【設置附件存放路徑】
*/

public void setAttachPath(String attachpath) {
this.saveAttachPath = attachpath;
}

/**
* 【設置日期顯示格式】
*/
public void setDateFormat(String format) throws Exception {
this.dateformat = format;
}

/**
* 【獲得附件存放路徑】
*/
public String getAttachPath() {
return saveAttachPath;
}

/**
* 【真正的保存附件到指定目錄里】
*/
private void saveFile(String fileName, InputStream in) throws Exception {
String osName = System.getProperty("os.name");
String storedir = getAttachPath();
String separator = "";
if (osName == null)
osName = "";
if (osName.toLowerCase().indexOf("win") != -1) {
separator = "\\";
if (storedir == null || storedir.equals(""))
storedir = "c:\\tmp";
} else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator + fileName);
System.out.println("storefile's path: " + storefile.toString());
// for(int i=0;storefile.exists();i++){
// storefile = new File(storedir+separator+fileName+i);
// }
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失敗!");
} finally {
bos.close();
bis.close();
}
}

public static void main(String[] args) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
"dt_cj2004", "abcdefghij");
Store store = session.getStore(urln);
store.connect();

Folder folder = store.getFolder("spool");
//Folder folder = store.getFullName();

folder.open(Folder.READ_ONLY);
//System.out.println(folder.getNewMessageCount());

Message message[] = folder.getMessages();
System.out.println("Messages's length: " + message.length);
ReciveOneMail pmm = null;
/*

for (int i = 0; i < message.length; i++) {
System.out.println("======================");
pmm = new ReciveOneMail((MimeMessage) message[i]);
System.out
.println("Message " + i + " subject: " + pmm.getSubject());
System.out.println("Message " + i + " sentdate: "
+ pmm.getSentDate());
System.out.println("Message " + i + " replysign: "
+ pmm.getReplySign());
System.out.println("Message " + i + " hasRead: " + pmm.isNew());
System.out.println("Message " + i + " containAttachment: "
+ pmm.isContainAttach((Part) message[i]));
System.out.println("Message " + i + " form: " + pmm.getFrom());
System.out.println("Message " + i + " to: "
+ pmm.getMailAddress("to"));
System.out.println("Message " + i + " cc: "
+ pmm.getMailAddress("cc"));
System.out.println("Message " + i + " bcc: "
+ pmm.getMailAddress("bcc"));
pmm.setDateFormat("yy年MM月dd日 HH:mm");
System.out.println("Message " + i + " sentdate: "
+ pmm.getSentDate());
System.out.println("Message " + i + " Message-ID: "
+ pmm.getMessageId());
// 獲得郵件內容===============
pmm.getMailContent((Part) message[i]);
System.out.println("Message " + i + " bodycontent: \r\n"
+ pmm.getBodyText());
pmm.setAttachPath("c:\\");
pmm.saveAttachMent((Part) message[i]);
}
*/
}
}

package com.gwxc.hz.mail.demo;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MyMailTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception {

// 會話===========================
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");// 需要驗證
Session session = Session.getDefaultInstance(props, null);

// msg 設置=======================
MimeMessage mimeMsg = new MimeMessage(session);

// 設置標題
mimeMsg.setSubject("標題test");

// 設置內容----begin
Multipart mp = new MimeMultipart();

// 添加文本
BodyPart bp1 = new MimeBodyPart();
bp1.setContent("文本內容", "text/html;charset=GB2312");
mp.addBodyPart(bp1);

// 添加附件
BodyPart bp2 = new MimeBodyPart();
FileDataSource fileds = new FileDataSource("c:\\boot.ini");
bp2.setDataHandler(new DataHandler(fileds));
bp2.setFileName(fileds.getName());
mp.addBodyPart(bp2);

mimeMsg.setContent(mp);
// 設置內容----end

mimeMsg.setFrom(new InternetAddress("[email protected]"));
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
.parse("[email protected]"));
mimeMsg.saveChanges();

// 傳輸==================================
Transport transport = session.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"),
"xiangzhengyan", "pass");
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
transport.close();
}

}

㈢ javamail怎麼設置代理發送郵件

public static void main(String[] args) throws Exception {
MailTest test = new MailTest();
//通過代理發送郵件
test.sendMailByProxy();
}
private void sendMailByProxy()throws Exception{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//設置代理伺服器
Properties props = System.getProperties();
props.setProperty("proxySet", "true");
props.setProperty("socksProxyHost", "192.168.1.1");
props.setProperty("socksProxyPort", "1080");
props.setProperty("mail.smtp.host", "smtp.163.com");

//props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "用戶名";
final String password = "密碼";

//使用驗證
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username,
password);
}
});
MimeMessage message = new MimeMessage(session);
Address address = new InternetAddress("[email protected]");
Address toAaddress = new InternetAddress("[email protected]");

message.setFrom(address);
message.setRecipient(MimeMessage.RecipientType.TO, toAaddress);
message.setSubject("測試");
message.setText("test");
message.setSentDate(new Date());
Transport.send(message);
System.out.println("郵件發送!");
}

㈣ 利用javamail和POP3、SMPT協議實現郵件的收發

一 簡介 SMTP 的全稱是 Simple Mail Transfer Protocol 即簡單郵件傳輸協議 用於郵件發送 SMTP 認證 簡單地說就是要求必須在提供了賬戶名和密碼之後才可以登錄 SMTP 伺服器 POP (Post Office Protocol )協議允許電子郵件客戶端下載伺服器上的郵件 但是在客戶端的操作(如移動郵件 標記已讀等) 不會反饋到伺服器上 比如通過客戶端收取了郵箱中的 封郵件並移動到其他文件夾 郵箱伺服器上的這些郵件是沒有同時被移動的 而IMAP(Internet Mail Access Protocol)提供webmail 與電子郵件客戶端之間的雙向通信 客戶端的操作都會反饋到伺服器上 對郵件進行的操作 伺服器上的郵件也會做相應的動作 同時 IMAP像POP 那樣提供了方便的郵件下載服務 讓用戶能進行離線閱讀 IMAP提供的摘要瀏覽功能可以讓你在閱讀完所有的郵件到達時間 主題 發件人 大小等信息後才作出是否下載的決定 此外 IMAP 更好地支持了從多個不同設備中隨時訪問新郵件 總之 IMAP 整體上為用戶帶來更為便捷和可靠的體驗 POP 更易丟失郵件或多次下載相同的郵件 但 IMAP 通過郵件客戶端與webmail 之間的雙向同步功能很好地避免了這些問題 注 若在web郵箱中設置了 保存到已發送 使用客戶端POP服務發信時 已發郵件也會自動同步到網頁端 已發送 文件夾內 二 利用SMTP協議發送郵件 package like email;import java io File;import java io UnsupportedEncodingException;import java util ArrayList;import java util Properties;import javax activation DataHandler;import javax activation DataSource;import javax activation FileDataSource;import javax mail Authenticator;import javax mail BodyPart;import javax mail Message;import javax mail MessagingException;import javax mail Multipart;import javax mail Session;import javax mail Transport;import javax mail internet AddressException;import javax mail internet InternetAddress;import javax mail internet MimeBodyPart;import javax mail internet MimeMessage;import javax mail internet MimeMultipart;/*** @author like* @E mail k* @CreateTime 下午 : : */public class SMTPSendTest {private static final int RECEIPT = ;private static final String attachmentDir = ;public static void sendEmail(Email emailInfo) throws UnsupportedEncodingException MessagingException {Properties props = new Properties() props put( mail *** tp host emailInfo getSmtpServer()) props put( mail *** tp port emailInfo getSmtpPort()) props put( mail *** tp auth true ) Authenticator auth = new SMTPAuthenticator(emailInfo getUsername() emailInfo getPassword()) Session session = Session getInstance(props auth) session setDebug(false) Message msg = new MimeMessage(session) msg setFrom(new InternetAddress(emailInfo getFrom() emailInfo getFromName())) msg setRecipients(Message RecipientType TO getEmailRecipient(emailInfo getTO())) msg setRecipients(Message RecipientType CC getEmailRecipient(emailInfo getCC())) msg setRecipients(Message RecipientType BCC getEmailRecipient(emailInfo getBCC())) if (emailInfo getReceipt() == RECEIPT) {msg setHeader( Disposition Notification To emailInfo getFrom()) }msg setSubject(emailInfo getSubject()) // 設置郵件內容(包括附件的HTML格式內容)msg setContent(getMultipart(emailInfo getContent() attachmentDir emailInfo getAttachment())) msg saveChanges() Transport send(msg) }/*** 封裝郵件地址** @param address* @return* @throws AddressException*/private static InternetAddress[] getEmailRecipient(ArrayList<String> address) throws AddressException {int toLen = ;if (address != null) {toLen = address size() }InternetAddress[] addressTo = new InternetAddress[toLen];if (toLen != ) {String m_st_email = ;for (int i = ; i < toLen; i++) {m_st_email = (String) address get(i) if (m_st_email != null)addressTo[i] = new InternetAddress(m_st_email trim()) }}return addressTo;}private static Multipart getMultipart(String text String attachParentDir ArrayList<String> attachment) throws MessagingException {

lishixin/Article/program/Java/hx/201311/26993

㈤ 急求:在JavaMail中,如何獲取messages中的所有「未讀」的郵件;通過uid能實現么具體是如何實現的呢

pop3由於本身不提供Flag的功能,所以一般來說沒有辦法判斷通過pop3得到的message是否已讀

但是有些服務商會在header裡面加入message是否已讀的信息
可以嘗試用message.getHeader(String name)得到header的信息,比如用
message.getHeader("Status")
或許可以得到是否已讀的信息(或許而已,因為這條語句成功與否取決於服務商是否加入該信息,以及使用的名字是否為"Status")
如果需要查看所有的header來判斷這個服務商是否加入了message的狀態信息,可以用
message.getAllHeaders() (返回的是Enumeration<Header>)
來獲取所有的header然後一個個檢查,如果裡面沒有的話,就沒有辦法了.

********************************************************

imap提供Flag,可以用
message.getFlags().getSystemFlags();
得到 Flag[], 然後去看其是否不為空,並且包括Flag.SEEN ,如果是,則為已讀,反之則未讀.

例如下面這個method可以返回message已讀的狀態 (true=已讀,false=未讀):

需要的imports:
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Flags.Flag;

代碼:
private boolean isRead(Message message)
throws MessagingException {
Flag[] flags = message.getFlags().getSystemFlags();
for (Flag f : flags) {
if (f.equals(Flag.SEEN))
return true;
}
return false;
}

希望這些可以幫到你

㈥ javamail異常

一般情況,為了保障用戶郵箱的安全,QQ郵箱設置了POP3/SMTP的開關。系統預設設置是「關閉」,在用戶需要POP3/SMTP功能時請「開啟」。關閉POP3/SMTP後,您將只能接受郵件,不能發送郵件。

如果不是因為設置問題,試試QQ重新更改下登錄密碼。這時郵箱密碼需要重新設置。

如果重設後沒有用,可以考慮過幾天試試,有可能QQ的郵件伺服器認為你發的郵件為垃圾郵件。網上搜索的答案中,目前沒有個定論,但是在QQ郵箱中,這種情況也是多見的。

閱讀全文

與javamail設置pop3相關的資料

熱點內容
win10cf網路異常怎麼辦 瀏覽:39
word文件怎麼做格子 瀏覽:914
機器人比賽編程軟體有哪些 瀏覽:2
守衛劍閣186經典版本 瀏覽:326
網工和大數據哪個好找工作 瀏覽:261
生成pdb文件 瀏覽:858
java推送rtmp伺服器 瀏覽:171
查看網路埠連接情況 瀏覽:419
java最流行的程序設計語言 瀏覽:36
excel文件巨大 瀏覽:843
17年中央1號文件全文 瀏覽:770
j2ee編程中的容器是什麼意思 瀏覽:356
linux在後台運行 瀏覽:699
百度雲文件轉存數量 瀏覽:350
js實現靜態頁面語言切換 瀏覽:375
數據中台交付架構師是做什麼的 瀏覽:497
微信語音包怎麼轉成手機文件 瀏覽:477
在終端打開文件夾 瀏覽:442
藍拳90版本能量9加點 瀏覽:41
動態血壓儀哪裡看到數據 瀏覽:449

友情鏈接