使用javax.mail發送郵件
步驟如下
- 導入javax.mail包,可以下載jar包或者是用Maven配置文件都可以
- 加載配置文件,并配置屬性
- 根據屬性新建郵件會話
- 由郵件會話新建一個消息對象
- 設置郵件內容
- 設置信件內容
- 發送郵件
Example
public static void sendMail(String fromMail, String user, String password, String toMail, String mailTitle, String mailContent) throws Exception {
//加載一個配置文件
Properties props = new Properties();
//smtp:簡單郵件傳輸協議
//設置郵件服務器名
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");//同時通過驗證
//設置環境信息
Session session = Session.getInstance(props);//根據屬性新建一個郵件會話
session.setDebug(true); //會打印一些調試信息。
//由郵件會話新建一個消息對象
MimeMessage message = new MimeMessage(session);
//設置郵件內容
message.setFrom(new InternetAddress(fromMail));//設置發件人的地址
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//設置收件人,并設置其接收類型為TO
message.setSubject(mailTitle);//設置標題
//設置信件內容
// message.setText(mailContent); //發送 純文本 郵件 todo
message.setContent(mailContent, "text/html;charset=gbk"); //發送HTML郵件,內容樣式比較豐富
message.setSentDate(new Date());//設置發信時間
message.saveChanges();//存儲郵件信息
//發送郵件
Transport transport = session.getTransport("smtp");
transport.connect(user, password);
transport.sendMessage(message, message.getAllRecipients());//發送郵件,其中第二個參數是所有已設好的收件人地址
transport.close();
}
That's all. Thank U~