JAVA使用IMAP、POP3、SMTP協議收發郵件

package com.gatgets.mail;


import java.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.Properties;


import javax.mail.Authenticator;

import javax.mail.FetchProfile;

import javax.mail.Folder;

import javax.mail.Message;

import javax.mail.Message.RecipientType;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Store;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeUtility;


/**

* 郵件工具類

* 需要導入mail.jar包(j2ee自帶)

* @author 王正鎮

* @date 2011-8-14

*/

public class EmailUtil {


private String username = null; // 郵箱用戶名

private String password = null; // 郵箱密碼


/**

* 傳入自己的郵箱用戶名和密碼

* @param username

* @param password

*/

public EmailUtil(String username, String password) {

this.username = username;

this.password = password;

}


/**

* 創建連接會話

* @param props

* @return

*/

public Session createSession(Properties props) {


Session session = Session.getInstance(props, new Authenticator() {

// 返回用戶名密碼認證

@Override

public PasswordAuthentication getPasswordAuthentication() {

PasswordAuthentication pa = new PasswordAuthentication(username, password);

return pa;

}

});


return session;

}


/**

* 發送郵件(需設置SMTP)

* @throws Exception 

*/

public void sendMail(Properties props, SendEmailMessage sem) throws Exception {


Session session = createSession(props);


// 消息

Message msg = new MimeMessage(session);

msg.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFrom()))[0]);

// TO爲初級收件人,CC爲郵件副本抄送,BCC應該是密祕抄送吧

msg.setRecipients(RecipientType.TO, InternetAddress.parse(sem.getRecipient()));

msg.setSubject(sem.getSubject());

msg.setText(sem.getText());

msg.setSentDate(new Date());


// 發送消息

Transport.send(msg);

}


/**

* 接收郵件(需設置POP3或SAMP)

* @throws Exception 

*/

public void receiveMail(Properties props, String protocol) throws Exception {


Session session = createSession(props);

Store store = session.getStore(protocol);

store.connect(); // 連接

Folder inbox = store.getFolder("INBOX"); // 進入根目錄

inbox.open(Folder.READ_WRITE); // 只讀方式

FetchProfile profile = new FetchProfile();

profile.add(FetchProfile.Item.ENVELOPE); // 獲取信封

Message[] msgs = inbox.getMessages(); // 得到所有郵件

inbox.fetch(msgs, profile); // 預獲取信息

// 打印

for (int i = 0; i < msgs.length; i++) {

System.out.println("發送時間:" + msgs[i].getSentDate());

System.out.println("發送人:" + decodeText(msgs[i].getFrom()[0].toString()));

System.out.println("大小:" + msgs[i].getSize());

System.out.println("標題:" + msgs[i].getSubject());

System.out.println("內容" + msgs[i].getContent());

System.out.println("-------------------");

}


store.close();

}


/**

* 處理中文編碼問題

* @param text

* @return

* @throws UnsupportedEncodingException

*/

private String decodeText(String text) throws UnsupportedEncodingException {


if (text == null) {

return null;

}


if (text.startsWith("=?GB") || text.startsWith("=?gb"))

text = MimeUtility.decodeText(text);

else

text = new String(text.getBytes("ISO8859_1"));

return text;

}

}


package com.gatgets.mail;


import java.util.Properties;


/**
* 郵件默認配置類
* 方法中的必要參好,可根據實際情況修改
* @author 王正鎮
* @date 2011-8-14
*/
public class DefaultConfigurer {


/**
* 獲取SMTP默認配置
* @return
*/
public static Properties getSMTP() {
Properties p = new Properties();
p.setProperty("mail.smtp.host", "smtp.qq.com"); // 按需要更改
p.setProperty("mail.smtp.protocol", "smtp");
p.setProperty("mail.smtp.port", "465");
p.setProperty("mail.smtp.auth", "true");
// SSL安全連接參數
p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.smtp.socketFactory.fallback", "false");
p.setProperty("mail.smtp.socketFactory.port", "465");
return p;
}
/**
* 獲取POP3收信配置
* @return
*/
public static Properties getPOP3() {
Properties p = new Properties();
p.setProperty("mail.pop3.host", "pop.qq.com"); // 按需要更改
p.setProperty("mail.pop3.port", "995");
// SSL安全連接參數
p.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.pop3.socketFactory.fallback", "false");
p.setProperty("mail.pop3.socketFactory.port", "995");
return p;}
/**
* 獲取IMAP收信配置
* @return
*/
public static Properties getIMAP() {
Properties p = new Properties();
p.setProperty("mail.imap.host", "imap.qq.com"); // 按需要更改
p.setProperty("mail.imap.port", "993");
// SSL安全連接參數
p.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.imap.socketFactory.fallback", "false");
p.setProperty("mail.imap.socketFactory.port", "993");
return p;}
}


package com.gatgets.mail;


/**
* 發送郵件消息包裝屬性類

* @author 王正鎮
* @date 2011-8-14
*/
public class SendEmailMessage {


private String type; // 格式類型,如 text/html;charset=gbk
private String from; // 發送人
private String subject; // 標題
private String text; // 內容
private String recipient; // 接收人,多個接收人用逗號分隔
private String datetime; // 發送時間


public String getFrom() {
return from;
}


public void setFrom(String from) {
this.from = from;
}


public String getSubject() {
return subject;
}


public void setSubject(String subject) {
this.subject = subject;
}


public String getText() {
return text;
}


public void setText(String text) {
this.text = text;
}


public String getRecipient() {
return recipient;
}


public void setRecipient(String recipient) {
this.recipient = recipient;
}


public String getDatetime() {
return datetime;
}


public void setDatetime(String datetime) {
this.datetime = datetime;
}


public String getType() {
return type;
}


public void setType(String type) {
this.type = type;
}


}


package com.gatgets.mail;


/**
* 測試類
* @author 王正鎮
* @date 2011-8-14
*/
public class TestEmail {


/**
* 程序入口點
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
// 默認情況下,在這裏輸入QQ號和密碼,便可收信與發信
EmailUtil eu = new EmailUtil("xxx", "xxx");
SendEmailMessage sem = new SendEmailMessage();
sem.setFrom("wzz<[email protected]>");
sem.setRecipient("[email protected],[email protected]");
sem.setSubject("鎮長");
sem.setText("hello world");
eu.sendMail(DefaultConfigurer.getSMTP(), sem);
System.out.println("發送成功");
// 收郵件
eu.receiveMail(DefaultConfigurer.getPOP3(), "pop3"); // pop3收信
System.out.println("收取完畢");
// 使用IMAP收信會拋出 Failed to load IMAP envelope 異常
//eu.receiveMail(DefaultConfigurer.getIMAP(), "imap"); // imap收信
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章