要運行此範例要先使用 javamail.jar 與 commons-email.jar。
以下我這兩個版本,建議你可以在這版本以上使用,或跟我用相同版本
版本 : commons-email : 1.5
版本 : javamail : 1.4.7
Jar 下載 : https://download.csdn.net/download/weixin_38884324/10785583
/**
作者 : 黃彥霖
主網站 : https://blog.csdn.net/weixin_38884324
本範例網站 : https://blog.csdn.net/weixin_38884324/article/details/84077859
*/
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class Test {
public static void main(String[] args) {
//String hostName = "smtp.gmail.com"; // Gmail 主機
String hostName = "smtp.qq.com"; // QQ 主機
String myMail = "[email protected]"; // 自己郵箱
String myPassword = "abcdefg"; // 自己郵箱密碼
String userName = "系統直發 Hello"; // 用戶名 : 可寫自己名子,例如 張三、小明、Andy、Steve
String title = "測試使用 SMTP SSL發信"; // 信件標題
String message = "<html><head><title>測試</title></head><body>這是一封測試信,收到請自行刪除 </body></html>"; // 內容
String targetMail = "[email protected]"; // 對方郵箱
try {
sendSmtpMail(hostName, myMail, myPassword, userName, title, message, targetMail);
System.out.println("郵件發送成功");
} catch (EmailException ex) {
System.err.println("郵件發送失敗 : " + ex.getMessage());
}
}
// 只發一封信 : 使用 SMTP 協議,預設端口 465,預設編碼 UTF-8,使用 SSL
public static void sendSmtpMail(String hostName, String myMail, String myPassword, String userName, String title, String message, String targetMail) throws EmailException {
Email email = new HtmlEmail();
email.setHostName(hostName);
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(myMail, myPassword));
email.setDebug(true);
email.setSSL(true);
email.setSslSmtpPort("465");
email.setCharset("UTF-8");
email.setSubject(title);
email.setFrom(myMail, userName);
email.setMsg(message);
email.addTo(targetMail);
email.send();
}
}