發送 Mail (SMTP) Server
需要 TLS or SSL:  smtp.gmail.com (使用身份驗證)
使用身份驗證: Yes
TLS/STARTTLS 的Port號: 587
SSL 的Port號: 465

GMail SMTP 設定資訊


範例:



import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GmailSendMailviaTLS {
public static void main(String args[]) {
String host = "smtp.gmail.com";
int port = 587;
final String username = "user@gmail.com";
final String password = "your password";//your password

Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", port);
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("fromn@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("測試寄信.");
message.setText("Dear Levin, \n\n 測試 測試 測試 測試 測試 測試 email !");

Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);

Transport.send(message);

System.out.println("寄送email結束.");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}


javax mail 的jar檔
maven pom.xml
<dependency>
<groupid>javax.mail</groupid>
<artifactid>mail</artifactid>
<version>1.4.7</version>
</dependency>

Download JAR URL  :


結果圖1


結果圖2



錯誤訊息:
 javax.mail.MessagingException: Could not connect to SMTP host: sm
tp.gmail.com, port: 587;

解決:
防火牆(firewall)或代理服務器(proxy) 阻止了。


錯誤訊息:
Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException

解決1:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});



解決2:

帳戶-> 安全性
圖1



安全性較低的應用程式存取權限 設定
圖2



設定 啟用
圖3




相關參考:

Send a Simple E-mail:















其它文章

arrow
arrow
    文章標籤
    java mail
    全站熱搜

    PG Levin Li 發表在 痞客邦 留言(0) 人氣()