JavaMail是一個用來寄Mail的Lib
如果架在Server上就只要設定好Server的Port和協定就好了
而如果要用Mail轉寄, 則需要多設定帳號密碼
這篇就介紹用Gmail的作法
1. 官網http://www.oracle.com/technetwork/java/javamail/index.html
2. 參考網頁http://www.ewdna.com/2009/12/javajavamailhtmlemail.html
3. 參考網頁http://www.rgagnon.com/javadetails/java-0321.html
4. 參考網頁https://stackoverflow.com/questions/43406528/javamail-api-username-and-password-not-accepted-gmail
5. 首先到Gmail -> 登入和安全性 -> 允許安全性較低的應用程式 打開
6. 到官網下載javax.mail的jar黨並加入
7. 將帳號密碼, 協定 還有port設定好
gmail要設定
String host = "smtp.gmail.com";
int port = 587;
而如果要用Yahoo的則是用"smtp.mail.yahoo.com";
8. 宣告Properties 設定屬性
測試時可以將debug打開
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
9. 然後設定seesion, 和寄信的Message, 最後再寄出就好了
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pw);
}});
try {
Message message = new MimeMessage(session);
// message.setFrom(new InternetAddress("寄信的Mail"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(objMail));
message.setSubject("測試標題");
message.setContent("測試內容", "text/html; charset=UTF-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}