最近工作比較閒,出於個人興趣,寫了個發送郵件的工具類。本次是通過163郵箱發送郵件,
相關jar包:javax.mail.*
package com.youxu.util;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
/**
* 這是一個工具類,各方面都兼容
*
* @param to
* 收件人郵箱
* @param code
* 必要時的用戶驗證
* @throws Exception
*/
public static void sendMail(String to, String code) throws Exception {
Properties props = new Properties();
// 設置服務器
props.setProperty("mail.smtp.host", "smtp.163.com");
// 設置權限,這是由於163.126.等等,公共郵件爲了發垃圾郵件需要設置的,
// 不然會報異常,553 authentication is
// required,smtp13,EcCowACXHjuxivpVRZHkCA--.51163S2 1442482875
props.put("mail.smtp.auth", "true");
// 1.Session對象.連接(與郵箱服務器連接)
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 設置發郵件帳號和密碼
return new PasswordAuthentication("y****@163.com", "*****");
}
});
// 2.構建郵件信息:
Message message = new MimeMessage(session);
// 發件人:
message.setFrom(new InternetAddress("***@163.com"));
// 收件人:
message.setRecipient(RecipientType.TO, new InternetAddress(to));
// 設置郵件的標題
message.setSubject("******");
// 設置正文,通過HTML標籤設置內容格式
message.setContent("<h1>*********</h1><h3>***********</h3>",
"text/html;charset=UTF-8");
// 3.發送對象
Transport.send(message);
}
}
代碼簡單明瞭,只需調用即可,參數看情況添加,
與大家共勉,謝謝!!!