1. 下載 JavaMail Library
http://www.oracle.com/technetwork/java/javamail/index-138643.html
我用的是 1.4.5
後來發現比較新的是 1.5.0
2. 使用JavaMail API
網路上很多範例, 尤其是使用Gmail SMTP server 的
建議有時間的話先看一下 the most common mistakes people make
另外, API 中有分 SSL 與 STARTTLS.
許多 Gmail SMTP 範例會分 SSL 與 TLS, 但範例中的 TLS 通常是指 STARTTLS , 容易誤導
關於 SSL, TLS, STARTTLS 的區分說明可看這篇
Note: 若要透過 Gmail 發信, 則該 Gmail 帳號需降低安全性, 修改方式可看這裡
3. Sample: SSL/TLS for my mail server
val host = "host.mymailserver.com"
val port = 465
val username = "myaccount"
val password = "mypasswd"
設定 connection property
val properties = System.getProperties
properties.put("mail.smtp.auth", "true")
properties.put("mail.smtp.ssl.enable", "true")
因為是未認證的 mail server, 另外加這段
properties.put("mail.smtp.ssl.checkserveridentity", "false")
properties.put("mail.smtp.ssl.trust", "*")
準備信件內容
val session = Session.getInstance(properties)
val message = new MimeMessage(session)
message.setFrom(new InternetAddress(" noreply@mymailserver.com"))
message.setRecipients(Message.RecipientType.TO, "receipient@gmail.com")
message.setSubject("Greetings")
message.setText( "THIS IS TEST MAIL")
connect & send mail
val transport = session.getTransport("smtp")
transport.connect(host, port, username, password)
transport.sendMessage(message, message.getAllRecipients)
transport.close()
參考資料
https://www.fastmail.com/help/technical/ssltlsstarttls.html
http://www.oracle.com/technetwork/java/javamail/faq/index.html
http://puremonkey2010.blogspot.tw/2010/12/java-javamail-gmail.html
沒有留言:
張貼留言