`
公园美丽
  • 浏览: 11890 次
社区版块
存档分类
最新评论

Spring Boot: Spring Boot 邮件服务

 
阅读更多

 

Spring Boot (十二): Spring Boot 邮件服务
 

 

最早我们发邮件的时候是使用 JavaMail 来发送邮件,而在 Spring Boot 中, Spring Boot 帮我们将 JavaMail 封装好了,是可以直接拿来使用的。(了解源码可+求求: 1791743380)

1. 依赖文件 pom.xml

代码清单:spring-boot-mail/pom.xml

Java代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.springframework.boot</groupId>  
  4.         <artifactId>spring-boot-starter-mail</artifactId>  
  5.     </dependency>  
  6.     <dependency>  
  7.         <groupId>org.springframework.boot</groupId>  
  8.         <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  9.     </dependency>  
  10.   
  11.     <dependency>  
  12.         <groupId>org.springframework.boot</groupId>  
  13.         <artifactId>spring-boot-starter-test</artifactId>  
  14.         <scope>test</scope>  
  15.     </dependency>  
  16. </dependencies>  

 

  • spring-boot-starter-thymeleaf 引入这个模版引擎是因为我们在发送邮件的时候,各种格式使用 HTML 的方式更容易实现,同样我们也可以使用 freeMark , Spring Boot 同样为我们提供了依赖包。

2. 配置文件 application.yml

代码清单:

Java代码  收藏代码
  1. server:  
  2.   port: 8080  
  3. spring:  
  4.   application:  
  5.     name: spring-boot-mail  
  6.   mail:  
  7.     host: smtp.qq.com  
  8.     username: 136736247  
  9.     password: xxxxxx  
  10.     default-encoding: UTF-8  
  11.     fromAddr: 136736247@qq.com  
  12.     nickName: inwsy  

 这里我使用 QQ 邮箱作为邮件的发送方,其中的 password 并不是我们的 QQ 密码,这个密码需要我们在 QQ 邮箱的设置里面自己申请的。如下图:

 

Spring Boot (十二): Spring Boot 邮件服务
 

 

其中的 spring.mail.fromAddr 和 spring.mail.nickName 这两个配置是我自己配置的,并不是官方的配置,后续我会在代码中读这两个配置项。

3. 简易邮件发送

3.1 实现类

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java

Java代码  收藏代码
  1. @Service  
  2. public class MailServiceImpl implements MailService {  
  3.   
  4.     private final Logger logger = LoggerFactory.getLogger(this.getClass());  
  5.   
  6.     @Autowired  
  7.     private JavaMailSender javaMailSender;  
  8.   
  9.     @Value("${spring.mail.fromAddr}")  
  10.     private String from;  
  11.   
  12.     @Value("${spring.mail.nickName}")  
  13.     private String nickName;  
  14.   
  15.     @Override  
  16.     public void sendSimpleEmail(String to, String subject, String content) {  
  17.         SimpleMailMessage simpleMailMessage = new SimpleMailMessage();  
  18.         simpleMailMessage.setFrom(nickName + "<" + from + ">");  
  19.         simpleMailMessage.setTo(to);  
  20.         simpleMailMessage.setSubject(subject);  
  21.         simpleMailMessage.setText(content);  
  22.   
  23.         try{  
  24.             javaMailSender.send(simpleMailMessage);  
  25.             logger.info("简易邮件发送成功");  
  26.         } catch(Exception e) {  
  27.             logger.error("简易邮件发送异常", e);  
  28.         }  
  29.   
  30.     }  
  31. }  

 

3.2 测试类

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java

Java代码  收藏代码
  1. @Autowired  
  2. MailService mailService;  
  3.   
  4. @Test  
  5. public void sendSimpleEmail() {  
  6.     mailService.sendSimpleEmail("inwsy@hotmail.com""测试邮件题目""测试邮件内容");  
  7. }  

 这里邮件发送至本人的 Hotmail 邮箱。

4. 发送 HTML 格式的邮件

4.1 实现类

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java

Java代码  收藏代码
  1. @Override  
  2. public void sendHTMLEmail(String to, String subject, String content) {  
  3.     MimeMessage message = javaMailSender.createMimeMessage();  
  4.   
  5.     try {  
  6.         MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);  
  7.   
  8.         messageHelper.setFrom(new InternetAddress(from, nickName, "UTF-8"));  
  9.         messageHelper.setTo(to);  
  10.         messageHelper.setSubject(subject);  
  11.         messageHelper.setText(content, true);  
  12.   
  13.         javaMailSender.send(message);  
  14.   
  15.         logger.info("HTML 模版邮件发送成功");  
  16.     } catch (MessagingException e) {  
  17.         logger.error("HTML 模版邮件发送失败", e);  
  18.     } catch (UnsupportedEncodingException e) {  
  19.         logger.error("收件地址编码异常", e);  
  20.     }  
  21.   
  22. }  

 

4.2 页面模版

代码清单:spring-boot-mail/src/main/resources/templates/email.html

Java代码  收藏代码
  1. <!DOCTYPE html>  
  2. <html lang="zh" xmlns:th="http://www.thymeleaf.org">  
  3.     <head>  
  4.         <meta charset="UTF-8"/>  
  5.         <title>邮件模版</title>  
  6.     </head>  
  7.     <body>  
  8.         这是邮件模版生成的邮件,可以点击链接查看详情。  
  9.         <a href="#" th:href="@{ http://www.geekdigging.com/ }">查看详情。</a>  
  10.         当前的Code为:<span th:text="${code}"></span>  
  11.     </body>  
  12. </html>  

 这里添加了动态内容 code ,在日常的开发中,我们使用发送验证码,动态生成内容是很有必要的。

4.3 测试类

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java

Java代码  收藏代码
  1. @Test  
  2. public void sendHTMLTemplateMail() {  
  3.     Context context = new Context();  
  4.     context.setVariable("code""123456");  
  5.     String emailHTMLContent = templateEngine.process("email", context);  
  6.   
  7.     mailService.sendHTMLEmail("inwsy@hotmail.com""测试 HTML 模版邮件", emailHTMLContent);  
  8. }  

 

5. 发送带附件的邮件

5.1 实现类

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java

Java代码  收藏代码
  1. @Override  
  2. public void sendAttachmentsMail(String to, String subject, String content, String fileName, String filePath) {  
  3.   
  4.     MimeMessage message = javaMailSender.createMimeMessage();  
  5.   
  6.     try {  
  7.         MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);  
  8.   
  9.         messageHelper.setFrom(new InternetAddress(from, nickName, "UTF-8"));  
  10.         messageHelper.setTo(to);  
  11.         messageHelper.setSubject(subject);  
  12.         messageHelper.setText(content, true);  
  13.   
  14.         FileSystemResource file = new FileSystemResource(new File(filePath));  
  15.         messageHelper.addAttachment(fileName, file);  
  16.   
  17.         javaMailSender.send(message);  
  18.   
  19.         logger.info("带附件邮件发送成功");  
  20.     } catch (MessagingException e) {  
  21.         logger.error("带附件邮件发送失败", e);  
  22.     } catch (UnsupportedEncodingException e) {  
  23.         logger.error("收件地址编码异常", e);  
  24.     }  
  25. }  

 注意: 如果需要发送多个附件,写多个 messageHelper.addAttachment(fileName, file); 即可。

5.2 测试类

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java

Java代码  收藏代码
  1. @Test  
  2. public void sendAttachmentsMail() {  
  3.   
  4.     String fileName = "图片.jpg";  
  5.     String filePath = "C:\\Users\\inwsy\\Downloads\\0370279582fe3e2a8012060c896a5dd.jpg";  
  6.   
  7.     mailService.sendAttachmentsMail("inwsy@hotmail.com""测试带附件的邮件""详细请查阅附件", fileName, filePath);  
  8. }  

 

6. 小结

在实际的开发过程中,邮件发送失败是一件比较经常出现的事情,比如:网络堵塞、对方拒收等情况,一般在邮件系统的设计中,可以先将要发送的数据写入数据中,等发送完成后再修改标记位,再增加一个保障机制,例如增加一个定时任务,将一段时间内,发送失败并重试次数小于一定阀值的内容再次进行发送,如果邮件系统的压力过大,可以选择使用异步的方式来进行发送,比如使用消息队列进行承压。

分享到:
评论

相关推荐

    Spring Boot:启动原理解析.docx

    Spring Boot:启动原理解析

    spring-boot-2.3.12.RELEASE-API文档-中文版.zip

    Maven坐标:org.springframework.boot:spring-boot:2.3.12.RELEASE; 标签:springframework、boot、spring、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览...

    Spring Boot 2 一步一步学微服务项目实战

    Spring Boot 2 一步一步学微服务项目实战 出版时间:2018-08-01

    Spring boot 示例 官方 Demo

    spring-boot-mail:spring boot和邮件服务 spring-boot-mongodb:spring boot和mongodb的使用 spring-boot-multi-mongodb:spring boot和mongodb多数据源的使用 spring-boot-package-war:spring-boot打包成war包...

    Spring Boot:数据库的操作案例

    1.Spring Boot 整合 JDBC 案例 2.Spring Boot 整合 Druid 数据源案例 3.Spring Boot 整合 MyBatis 案例 4.Spring Boot 整合 JPA 案例

    Beginning Spring Boot 2 Applications and Microservices with the Spring Framework

    This book will help you understand what Spring Boot is, how Spring Boot helps you build Spring-based applications quickly and easily, and the inner workings of Spring Boot using easy-to-follow ...

    spring-boot-configuration-processor-2.3.12.RELEASE-API文档-中文版.zip

    赠送jar包:spring-boot-configuration-processor-2.3.12....Maven坐标:org.springframework.boot:spring-boot-configuration-processor:2.3.12.RELEASE; 标签:springframework、boot、spring、configuration、proc

    Spring Boot Examples

    spring-boot-mail:spring boot和邮件服务 spring-boot-mongodb:spring boot和mongodb的使用 spring-boot-multi-mongodb:spring boot和mongodb多数据源的使用 spring-boot-package-war:spring-boot打包成war包...

    youlai-boot: Spring Boot 3 + Spring Security + Vue3 权限管理系统

    youlai-boot 是【有来开源组织】基于Spring Boot 3 + Spring Security 6 + JWT + Mybatis-Plus + Redis + XXL-Job + Vue3 等主流技术栈搭建的前后端分离权限管理系统。 在线预览地址:http://vue3.youlai.tech 后端...

    Pro Spring Boot 2第2版-2009-EPUB版

    Pro Spring Boot 2: An Authoritative Guide to Building Microservices, Web and Enterprise Applications, and Best Practices Quickly and productively develop complex Spring applications and microservices...

    Spring Boot 2 Recipes

    使用微服务进行Web服务开发并与Spring Boot应用程序集成 无缝添加持久性和数据层,使您的Spring Boot Web应用程序做得更多 使用Spring Boot集成企业服务以创建更复杂的Java应用程序 本书适用于经验丰富的Java和...

    Spring Boot参考指南-1.4.1.RELEASE

    GitBook : Spring Boot参考指南 整合示例:程序猿DD-Spring Boot教程 Email:qibaoguang@gmail.com 从这里开始 交流群: spring boot最佳实践2 : 460560346 spring boot最佳实践( 已满) :445015546 注 1.3版本...

    spring-boot-autoconfigure-2.5.5-API文档-中文版.zip

    Maven坐标:org.springframework.boot:spring-boot-autoconfigure:2.5.5; 标签:springframework、boot、spring、autoconfigure、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index....

    spring-boot-autoconfigure-2.6.3-API文档-中文版.zip

    Maven坐标:org.springframework.boot:spring-boot-autoconfigure:2.6.3; 标签:spring、autoconfigure、springframework、boot、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index....

    spring-boot-test-2.2.8.RELEASE-API文档-中文版.zip

    Maven坐标:org.springframework.boot:spring-boot-test:2.2.8.RELEASE; 标签:springframework、boot、spring、test、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,...

    Spring Boot整合FTPClient线程池的实现示例

    主要介绍了Spring Boot整合FTPClient线程池的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Pro.Spring.Boot.1942270003

    Pro Spring Boot is your authoritative hands-on practical guide for increasing your Spring Framework-based enterprise Java and cloud application productivity while decreasing development time using the...

    Pro Spring Boot(Apress,2016)

    Pro Spring Boot is your authoritative hands-on practical guide for increasing your Spring Framework-based enterprise Java and cloud application productivity while decreasing development time using the...

    12Spring Boot Admin:微服务应用监控1

    12Spring Boot Admin:微服务应用监控1

Global site tag (gtag.js) - Google Analytics