最近學習了通過Java Mail庫進行郵件發送,參考了不少資料,自己總結一下Java Mail的使用,大概從以下三個方面進行描述,本例子使用QQ郵箱作爲郵件服務器:
1. 配置郵件會話(session)
2. 配置簡單文本郵件消息(MimeMessage)
3. 發送郵件(Transport)
先介紹郵件屬性:收件人(多個),抄送(多個),密送(多個),主體,正文,附件等。
直接上代碼:
<!-- 引入java mail包 -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
1.配置郵件會話
public static Session getMailSession(){
Properties properties = new Properties();
//服務器主機名
properties.put("mail.host","smtp.qq.com");
//協議名稱
properties.put("mail.transport.protocol","smtps");
//發送服務器需要身份驗證
properties.put("mail.smtp.auth","true");
//設置ssl加密(QQ郵箱必須設置)
properties.put("mail.smtp.ssl.enable","true");
//創建session
Session session = Session.getDefaultInstance(properties);//獲取共享session
//開啓DEBUG模式,監視發郵件狀態
session.setDebug(true);
return session;
}
2.配置簡單文本郵件消息
/**
* 生成普通文本郵件
* @param session
* @return
* @throws MessagingException
*/
public static MimeMessage createSimpleMessage(Session session) throws Exception {
//創建郵件
MimeMessage message = new MimeMessage(session);
//發件人
message.setFrom("[email protected]");
//收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
//標題
message.setSubject("簡單郵件");
//To: 增加收件人(可選)
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]", "USER_DD", "UTF-8")); //InternetAddress 第二個參數是別名
//Cc: 抄送(可選)
message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("[email protected]", "USER_EE", "UTF-8"));
//Bcc: 密送(可選)
message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("[email protected]", "USER_FF", "UTF-8"));
InternetAddress[] addressArr = new InternetAddress[1];
addressArr[0] = new InternetAddress("[email protected]", "xxx", "UTF-8");
//郵件回覆接收人
message.setReplyTo(addressArr);
//封裝MIME消息
MimeBodyPart text = new MimeBodyPart();
text.setContent("你好啊!", "text/html; charset=UTF-8");
//組合MIME消息
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(text);
//設置郵件內容
message.setContent(multipart);
message.saveChanges();
return message;
}
3.發送郵件(Transport)
public static void sendEmail(MimeMessage msg, Session session) throws Exception {
//得到transport對象
Transport transport = session.getTransport();
//連接郵件服務器(qq郵箱需要使用授權碼)password爲qq郵箱授權碼
//(***此處郵箱必須和發件人一致***)
transport.connect("smtp.qq.com", "[email protected]", "password");
//發送郵件
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
使用QQ郵箱發送郵件需要使用授權碼作爲密碼,授權碼獲取方式如下:
- 進入QQ郵箱設置界面
- 開啓SMTP服務,生成授權碼