使用SpringBoot发送mail邮件

1、前言

发送邮件应该是网站的必备拓展功能之一,注册验证,忘记密码或者是给用户发送营销信息。正常我们会用JavaMail相关api来写发送邮件的相关代码,但现在springboot提供了一套更简易使用的封装。

 

2、Mail依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. <version>${spring-boot-mail.version}</version>
  5. </dependency>

来看看其依赖树:

可以看到spring-boot-starter-mail-xxx.jar对Sun公司的邮件api功能进行了相应的封装。

 

3、Mail自动配置类: MailSenderAutoConfiguration

其实肯定可以猜到Spring Boot对Mail功能已经配置了相关的基本配置信息,它是Spring Boot官方提供,其类为MailSenderAutoConfiguration

  1. //MailSenderAutoConfiguration
  2. @Configuration
  3. @ConditionalOnClass({ MimeMessage.class, MimeType.class })
  4. @ConditionalOnMissingBean(MailSender.class)
  5. @Conditional(MailSenderCondition.class)
  6. @EnableConfigurationProperties(MailProperties.class)
  7. @Import(JndiSessionConfiguration.class)
  8. public class MailSenderAutoConfiguration {
  9. private final MailProperties properties;
  10. private final Session session;
  11. public MailSenderAutoConfiguration(MailProperties properties,
  12. ObjectProvider<Session> session) {
  13. this.properties = properties;
  14. this.session = session.getIfAvailable();
  15. }
  16. @Bean
  17. public JavaMailSenderImpl mailSender() {
  18. JavaMailSenderImpl sender = new JavaMailSenderImpl();
  19. if (this.session != null) {
  20. sender.setSession(this.session);
  21. }
  22. else {
  23. applyProperties(sender);
  24. }
  25. return sender;
  26. }
  27. //other code...
  28. }

首先,它会通过注入Mail的属性配置类MailProperties

  1. @ConfigurationProperties(prefix = "spring.mail")
  2. public class MailProperties {
  3. private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  4. /**
  5. * SMTP server host.
  6. */
  7. private String host;
  8. /**
  9. * SMTP server port.
  10. */
  11. private Integer port;
  12. /**
  13. * Login user of the SMTP server.
  14. */
  15. private String username;
  16. /**
  17. * Login password of the SMTP server.
  18. */
  19. private String password;
  20. /**
  21. * Protocol used by the SMTP server.
  22. */
  23. private String protocol = "smtp";
  24. /**
  25. * Default MimeMessage encoding.
  26. */
  27. private Charset defaultEncoding = DEFAULT_CHARSET;
  28. /**
  29. * Additional JavaMail session properties.
  30. */
  31. private Map<String, String> properties = new HashMap<String, String>();
  32. /**
  33. * Session JNDI name. When set, takes precedence to others mail settings.
  34. */
  35. private String jndiName;
  36. /**
  37. * Test that the mail server is available on startup.
  38. */
  39. private boolean testConnection;
  40. //other code...
  41. }

MailSenderAutoConfiguration自动配置类中,创建了一个Bean,其类为JavaMailSenderImpl,它是Spring专门用来发送Mail邮件的服务类,SpringBoot也使用它来发送邮件。它是JavaMailSender接口的实现类,通过它的send()方法来发送不同类型的邮件,主要分为两类,一类是简单的文本邮件,不带任何html格式,不带附件,不带图片等简单邮件,还有一类则是带有html格式文本或者链接,有附件或者图片的复杂邮件。

 

4、发送邮件

通用配置application.properties:

  1. # 设置邮箱主机
  2. spring.mail.host=smtp.qq.com
  3. # 设置用户名
  4. spring.mail.username=xxxxxx@qq.com
  5. # 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
  6. spring.mail.password=pwvtabrwxogxidac
  7. # 设置是否需要认证,如果为true,那么用户名和密码就必须的,
  8. # 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
  9. spring.mail.properties.mail.smtp.auth=true
  10. # STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
  11. spring.mail.properties.mail.smtp.starttls.enable=true
  12. spring.mail.properties.mail.smtp.starttls.required=true
  13. mail.from=${spring.mail.username}
  14. mail.to=yyyyyy@qq.com

由于使用QQ邮箱的用户占多数,所以这里选择QQ邮箱作为测试。还有注意的是spring.mail.password这个值不是QQ邮箱的密码,而是QQ邮箱给第三方客户端邮箱生成的授权码。具体要登录QQ邮箱,点击设置,找到SMTP服务:

默认SMTP服务是关闭的,即默认状态为关闭状态,如果是第一次操作,点击开启后,会通过验证会获取到授权码;而我之前已经开启过SMTP服务,所以直接点击生成授权码后通过验证获取到授权码。

 

自定义的MailProperties配置类,用于解析mail开头的配置属性:

  1. @Component
  2. @ConfigurationProperties(prefix = "mail")
  3. public class MailProperties {
  4. private String from;
  5. private String to;
  6. //getter and setter...
  7. }

 

4.1、测试发送简单文本邮件

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. public class SimpleMailTest {
  4. @Autowired
  5. private MailService mailService;
  6. @Test
  7. public void sendMail(){
  8. mailService.sendSimpleMail("测试Springboot发送邮件", "发送邮件...");
  9. }
  10. }

sendSimpleMail()

  1. @Override
  2. public void sendSimpleMail(String subject, String text) {
  3. SimpleMailMessage mailMessage = new SimpleMailMessage();
  4. mailMessage.setFrom(mailProperties.getFrom());
  5. mailMessage.setTo(mailProperties.getTo());
  6. mailMessage.setSubject(subject);
  7. mailMessage.setText(text);
  8. javaMailSender.send(mailMessage);
  9. }

观察结果:

4.2、测试发送带有链接和附件的复杂邮件

事先准备一个文件file.txt,放在resources/public/目录下。

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. public class MimeMailTest {
  4. @Autowired
  5. private MailService mailService;
  6. @Test
  7. public void testMail() throws MessagingException {
  8. Map<String, String> attachmentMap = new HashMap<>();
  9. attachmentMap.put("附件", "file.txt的绝对路径");
  10. mailService.sendHtmlMail("测试Springboot发送带附件的邮件", "欢迎进入<a href=\"http://www.baidu.com\">百度首页</a>", attachmentMap);
  11. }
  12. }

sendHtmlMail():

  1. @Override
  2. public void sendHtmlMail(String subject, String text, Map<String, String> attachmentMap) throws MessagingException {
  3. MimeMessage mimeMessage = javaMailSender.createMimeMessage();
  4. //是否发送的邮件是富文本(附件,图片,html等)
  5. MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
  6. messageHelper.setFrom(mailProperties.getFrom());
  7. messageHelper.setTo(mailProperties.getTo());
  8. messageHelper.setSubject(subject);
  9. messageHelper.setText(text, true);//重点,默认为false,显示原始html代码,无效果
  10. if(attachmentMap != null){
  11. attachmentMap.entrySet().stream().forEach(entrySet -> {
  12. try {
  13. File file = new File(entrySet.getValue());
  14. if(file.exists()){
  15. messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
  16. }
  17. } catch (MessagingException e) {
  18. e.printStackTrace();
  19. }
  20. });
  21. }
  22. javaMailSender.send(mimeMessage);
  23. }

观察结果:

4.3、测试发送模版邮件

这里使用Freemarker作为模版引擎。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-freemarker</artifactId>
  4. <version>${spring-boot-freemarker.version}</version>
  5. </dependency>

事先准备一个模版文件mail.ftl

  1. <html>
  2. <body>
  3. <h3>你好, <span style="color: red;">${username}</span>, 这是一封模板邮件!</h3>
  4. </body>
  5. </html>

模版测试类:

  1. @SpringBootTest
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. public class MailTemplateTest {
  4. @Autowired
  5. private MailService mailService;
  6. @Test
  7. public void testFreemarkerMail() throws MessagingException, IOException, TemplateException {
  8. Map<String, Object> params = new HashMap<>();
  9. params.put("username", "Cay");
  10. mailService.sendTemplateMail("测试Springboot发送模版邮件", params);
  11. }
  12. }

sendTemplateMail():

  1. @Override
  2. public void sendTemplateMail(String subject, Map<String, Object> params) throws MessagingException, IOException, TemplateException {
  3. MimeMessage mimeMessage = javaMailSender.createMimeMessage();
  4. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  5. helper.setFrom(mailProperties.getFrom());
  6. helper.setTo(mailProperties.getTo());
  7. Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
  8. configuration.setClassForTemplateLoading(this.getClass(), "/templates");
  9. String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
  10. helper.setSubject(subject);
  11. helper.setText(html, true);//重点,默认为false,显示原始html代码,无效果
  12. javaMailSender.send(mimeMessage);
  13. }

观察结果:

原文地址:https://blog.csdn.net/caychen/article/details/82887926
posted @ 2019-07-30 17:00  星朝  阅读(1271)  评论(0编辑  收藏  举报