本文主要是說明 如何用 JavaMail 透過 Amazon SES 寄信 。
有時候需要一個穩定的 SMTP 主機來幫忙寄訊息,除了自己架主機和透過 Gmail 以外,Amazon 也有一個雲端服務叫做 Amazon SES (Simple Email Service) 可以利用。玩了一下,在考慮不想付費的情況下:
- 一開啟服務後你就有了一個測試環境(Sandbox),每天可以免費寄200封信給你登記並"通過認證的收件人"。
- 通過認證的收信人就是,Amazon 會寄封認證信給該收件人,該收件人點信中連結回覆就算通過認證了(就跟一般網站認證很像)。
- 申請並通過 SES Production Access 後,每天可以免費寄2000封信給"任意收件人"。
程式碼很短但事前步驟有點小多,筆記一下怕以後要用到時又會忘掉。
參考
事前準備
- 註冊 Amazon Web Service 帳號。
- 取得 Sandbox 環境或是更進一步取得 SES Production Access 環境。
- Sandbox 環境
- SES Production Access 環境
- 如果你每天想要寄超過200封信,或是有寄給陌生人的需求,就要填寫表格申請轉換至 SES Production Access,審核結果會在24小時內完成。
- 通過前面兩個步驟後,就可以透過 Web Console, AWS SDK 來寄送,但若是用 SMTP 來寄信,必須要到 SES 主控台,進入 SMTP Settings>Create My SMTP Credentials 建立一組帳號密碼。
參考
程式碼
提醒!!
- 記得專案要 include Java Mail 的 jar 檔。
- 記得去 SES 主控台建立 SMTP Credentials 取得帳號密碼。
我按官方這篇 Sending an Email Through the Amazon SES SMTP Interface with Java 會發生 java.lang.SecurityException: Access to default session denied ,所以改了一個自己的版本如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void send(String senderMail, String senderName, List<String> receiverList, String subject, String content) | |
{ | |
LOGGER.info("send"); | |
Properties props = System.getProperties(); | |
props.put("mail.transport.protocol", "smtp"); | |
props.put("mail.smtp.host", "email-smtp.us-west-2.amazonaws.com"); // 到https://console.aws.amazon.com/ses/下的SMTP Setting可以你的主機位址 | |
props.put("mail.smtp.port", 25); | |
props.put("mail.smtp.auth", "true"); | |
props.put("mail.smtp.starttls.enable", "true"); | |
props.put("mail.smtp.starttls.required", "true"); | |
Session mailSession = Session.getInstance(props, | |
new javax.mail.Authenticator() | |
{ | |
protected PasswordAuthentication getPasswordAuthentication() | |
{ | |
return new PasswordAuthentication( | |
"填入SMTP Credentials的帳號", "填入SMTP Credentials的密碼"); | |
} | |
}); | |
try | |
{ | |
Message msg = new MimeMessage(mailSession); | |
msg.setFrom(new InternetAddress(senderMail, senderName, "UTF-8")); | |
for (int i = 0; i < receiverList.size(); i++) | |
{ | |
String receiver = receiverList.get(i); | |
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); | |
} | |
msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B") ); | |
msg.setContent(content, "text/html; charset=UTF-8"); | |
Transport.send(msg); | |
} | |
catch (AddressException e) | |
{ | |
LOGGER.error(e.getLocalizedMessage()); | |
e.printStackTrace(); | |
} | |
catch (MessagingException e) | |
{ | |
LOGGER.error(e.getLocalizedMessage()); | |
e.printStackTrace(); | |
} | |
catch (UnsupportedEncodingException e) | |
{ | |
LOGGER.error(e.getLocalizedMessage()); | |
e.printStackTrace(); | |
} | |
} |
參考