AWS:使用 SES 发送邮件 Java 代码

用 Java 在 AWS 调用邮件接口:

可能需要用到的 jar 包,如图:

AWS:使用 SES 发送邮件 Java 代码

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
 public void sendEmailBySmtp(MessageVo emailSentRecord) throws Exception {
 Properties props = System.getProperties();
 props.put("mail.transport.protocol", "smtp");
 props.put("mail.smtp.port", 587);
 props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.auth", "true");
 Session session = Session.getDefaultInstance(props);
 MimeMessage msg = new MimeMessage(session);
 String smtpUserName = "xxxxxxxx"; // 带有权限的 AWS 帐号
 String smtpUserPassword = "xxxxxxxx"; // 带有权限的 AWS 密码
 msg.setFrom(new InternetAddress("xxxx@xxxxxxx.xxx")); // 发送的 email 帐号 
 msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(emailSentRecord.getToMailAddress()));
 msg.setSubject(emailSentRecord.getSubject());
 msg.setContent(emailSentRecord.getContent(), "text/html");
 Transport transport = session.getTransport();
 try {
 transport.connect("email-smtp." + "us-east-1" + ".amazonaws.com",
 smtpUserName, smtpUserPassword);
 transport.sendMessage(msg, msg.getAllRecipients());
 //System.out.println("success post");
 } catch (Exception ex) {
 ex.printStackTrace();
 throw new RuntimeException();
 } finally {
 transport.close();
 }
 //System.out.println("enter end");
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

MessageVo:

public class MessageVo {
 private String subject;
 private String toMailAddress;
 private String content;
 public String getSubject() {
 return subject;
 }
 public void setSubject(String subject) {
 this.subject = subject;
 }
 public String getToMailAddress() {
 return toMailAddress;
 }
 public String getContent() {
 return content;
 }
 public void setContent(String content) {
 this.content = content;
 }
 public void setToMailAddress(String toMailAddress) {
 this.toMailAddress = toMailAddress;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

发送邮件的测试代码:

public static void main(String[] args){
 try {
 SendEmail sendEmail = new SendEmail();
 MessageVo messageVo = new MessageVo();
 messageVo.setSubject("error message");
 messageVo.setContent("product environment get something error");
 messageVo.setToMailAddress("anckkow@163.com"); // 接受邮件的帐号
 sendEmail.sendEmailBySmtp(messageVo);
 System.out.println("email send success");
 } catch (Exception e) {
 e.printStackTrace();
 }
 System.out.println("email send end");
 }

AWS:使用 SES 发送邮件 Java 代码

相关推荐