AWS:使用 SES 发送邮件 Java 代码
用 Java 在 AWS 调用邮件接口:
可能需要用到的 jar 包,如图:
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("[email protected]")); // 发送的 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("[email protected]"); // 接受邮件的帐号 sendEmail.sendEmailBySmtp(messageVo); System.out.println("email send success"); } catch (Exception e) { e.printStackTrace(); } System.out.println("email send end"); }
相关推荐
byn 2020-11-19
Dancen 2020-10-20
guchengxinfen 2020-10-12
SirLZF 2020-10-10
evolone 2020-10-09
AWS爽 2020-09-21
wolfjin 2020-09-10
lilu 2020-09-08
frank0 2020-08-26
wl00 2020-08-26
QFYJTL 2020-08-23
JokerCch 2020-08-17
zwb 2020-08-14
bendan 2020-08-13
酌希 2020-08-04
快乐de馒头 2020-07-29
Dramer0 2020-07-09
黑夜流星 2020-06-28
swazerz 2020-06-22