原文: https://howtodoinjava.com/spring-boot2/send-email-with-attachment/

了解如何借助JavaMailSender在 spring boot 应用程序中发送电子邮件,以发送简单电子邮件以及带有附件的电子邮件。

1. Maven

在 Spring Boot 应用程序中,包括spring-boot-starter-mail依赖项。

pom.xml

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.8.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-mail</artifactId>
  14. </dependency>
  15. </dependencies>

2. SMTP 配置

使用 spring boot,我们可以在application.properties文件中配置 SMTP 设置。

2.1. 邮箱

application.properties

  1. debug=true
  2. spring.mail.host=smtp.gmail.com
  3. spring.mail.port=25
  4. spring.mail.username=admin@gmail.com
  5. spring.mail.password=xxxxxx
  6. # Other properties
  7. spring.mail.properties.mail.debug=true
  8. spring.mail.properties.mail.transport.protocol=smtp
  9. spring.mail.properties.mail.smtp.auth=true
  10. spring.mail.properties.mail.smtp.connectiontimeout=5000
  11. spring.mail.properties.mail.smtp.timeout=5000
  12. spring.mail.properties.mail.smtp.writetimeout=5000
  13. # TLS , port 587
  14. spring.mail.properties.mail.smtp.starttls.enable=true
  15. # SSL, post 465
  16. #spring.mail.properties.mail.smtp.socketFactory.port = 465
  17. #spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory

为了能够使用两因素身份验证并关闭“允许不太安全的应用程序”选项,强烈建议使用应用程序密码代替 Gmail 密码。

请参阅:https://support.google.com/accounts/answer/185833

如果您可以访问下面的 SMTP 服务器,请在下面自由使用。

2.2. Outlook

如果它是某些公司服务器,请从管理员那里查找此信息。

Outlook Configuration

  1. spring.mail.host=smtp-mail.outlook.com
  2. spring.mail.port=587
  3. spring.mail.username=outlookuserid@outlook.com
  4. spring.mail.password=xxxxxx
  5. spring.mail.properties.mail.protocol=smtp
  6. spring.mail.properties.mail.tls=true
  7. spring.mail.properties.mail.smtp.auth=true
  8. spring.mail.properties.mail.smtp.starttls.enable=true
  9. spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com

2.3. AWS SES

从您的 AWS 设置页面中找到相关配置。阅读更多

AWS SES Configuration

  1. spring.mail.host=email-smtp.us-east-1.amazonaws.com
  2. spring.mail.port=465
  3. spring.mail.username=xxxxxxxxxxx
  4. spring.mail.password=xxxxxxxxxxx
  5. spring.mail.properties.mail.smtp.starttls.enable=true
  6. spring.mail.properties.mail.smtp.starttls.required=true
  7. spring.mail.properties.mail.smtp.ssl.enavle=true
  8. spring.mail.properties.mail.protocol=smtps
  9. spring.mail.properties.mail.smtps.auth=true

3. 预先配置的电子邮件模板

我们可以创建电子邮件模板以供每次重用 – 我们必须定期或在任何特定事件或持续时间内发送电子邮件。 在给定的示例中,我们正在使用SimpleMailMessage创建一个非常简单的纯文本电子邮件。

EmailConfig.java

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.mail.SimpleMailMessage;
  4. @Configuration
  5. public class EmailConfig
  6. {
  7. @Bean
  8. public SimpleMailMessage emailTemplate()
  9. {
  10. SimpleMailMessage message = new SimpleMailMessage();
  11. message.setTo("user@gmail.com");
  12. message.setFrom("admin@gmail.com");
  13. message.setSubject("Important email");
  14. message.setText("FATAL - Application crash. Save your job !!");
  15. return message;
  16. }
  17. }

4. 发送简单的电子邮件

为了发送不同类型的电子邮件,我们创建了一个EmailService类,该类可以采用在发送电子邮件之前在电子邮件中设置所需的参数。

EmailService.java

  1. @Service("emailService")
  2. public class EmailService
  3. {
  4. @Autowired
  5. private JavaMailSender mailSender;
  6. @Autowired
  7. private SimpleMailMessage preConfiguredMessage;
  8. /**
  9. * This method will send compose and send the message
  10. * */
  11. public void sendMail(String to, String subject, String body)
  12. {
  13. SimpleMailMessage message = new SimpleMailMessage();
  14. message.setTo(to);
  15. message.setSubject(subject);
  16. message.setText(body);
  17. mailSender.send(message);
  18. }
  19. /**
  20. * This method will send a pre-configured message
  21. * */
  22. public void sendPreConfiguredMail(String message)
  23. {
  24. SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
  25. mailMessage.setText(message);
  26. mailSender.send(mailMessage);
  27. }
  28. }

5. 发送带有附件的电子邮件

使用MimeMessageHelper发送多媒体电子邮件,该电子邮件用于配置MimeMessage。 这些 mime 消息是富文本电子邮件。

Email with attachment

  1. @Autowired
  2. private JavaMailSender mailSender;
  3. public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach)
  4. {
  5. MimeMessagePreparator preparator = new MimeMessagePreparator()
  6. {
  7. public void prepare(MimeMessage mimeMessage) throws Exception
  8. {
  9. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
  10. mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
  11. mimeMessage.setSubject(subject);
  12. mimeMessage.setText(body);
  13. FileSystemResource file = new FileSystemResource(new File(fileToAttach));
  14. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  15. helper.addAttachment("logo.jpg", file);
  16. }
  17. };
  18. try {
  19. mailSender.send(preparator);
  20. }
  21. catch (MailException ex) {
  22. // simply log it and go on...
  23. System.err.println(ex.getMessage());
  24. }
  25. }

6. 发送带有内嵌图像的电子邮件

富文本格式包括介于文本内容之间的媒体内容。 为此,我们必须使用MimeMessageHelperaddInline()方法。

Email with inline images

  1. @Autowired
  2. private JavaMailSender mailSender;
  3. public void sendMailWithInlineResources(String to, String subject, String fileToAttach)
  4. {
  5. MimeMessagePreparator preparator = new MimeMessagePreparator()
  6. {
  7. public void prepare(MimeMessage mimeMessage) throws Exception
  8. {
  9. mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
  10. mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
  11. mimeMessage.setSubject(subject);
  12. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  13. helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
  14. FileSystemResource res = new FileSystemResource(new File(fileToAttach));
  15. helper.addInline("identifier1234", res);
  16. }
  17. };
  18. try {
  19. mailSender.send(preparator);
  20. }
  21. catch (MailException ex) {
  22. // simply log it and go on...
  23. System.err.println(ex.getMessage());
  24. }
  25. }

7. Spring Boot 发送电子邮件演示

要使用上述配置发送电子邮件,请更新application.properties文件中的spring.mail.usernamespring.mail.password属性。

现在执行EmailService的方法发送电子邮件。

Application.java

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.boot.CommandLineRunner;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. public class Application implements CommandLineRunner
  7. {
  8. @Autowired
  9. private EmailService emailService;
  10. public static void main(String[] args) {
  11. SpringApplication.run(Application.class, args);
  12. }
  13. @Override
  14. public void run(String... args)
  15. {
  16. emailService.sendMail("lokeshgupta1981@gmail.com", "Hi", "Ho ho ho");
  17. emailService.sendPreConfiguredMail("Ho ho ho");
  18. }
  19. }

请给我发送有关通过 SpringBoot发送电子邮件的问题。

学习愉快!

下载源码