经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot 整合邮件服务
来源:cnblogs  作者:seolas  时间:2023/5/4 9:20:16  对本文有异议

参考教程

首先参考了 Spring Boot整合邮件配置,这篇文章写的很好,按照上面的操作一步步走下去就行了。

遇到的问题

版本配置

然后因为反复配置版本很麻烦,所以参考了 如何统一引入 Spring Boot 版本?

FreeMarker

在配置 FreeMarker 时,发现找不到 FreeMarkerConfigurer 类,参考了 springboot整合Freemark模板(详尽版) 发现要添加 web 模块。

测试注解

在使用测试类的时候,我只添加了 @SpringBootTest 注解,报空指针,参考了 测试类的@RunWith与@SpringBootTest注解 发现还要添加 @RunWith(SpringRunner.class) 注解。

实践结果

代码地址

完成的项目地址

核心代码

pom.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>fun.seolas</groupId>
  7. <artifactId>spring-boot-mail-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.3.2.RELEASE</version>
  13. </parent>
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-mail</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-test</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-freemarker</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-web</artifactId>
  30. </dependency>
  31. </dependencies>
  32. <build>
  33. <plugins>
  34. <plugin>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-maven-plugin</artifactId>
  37. </plugin>
  38. </plugins>
  39. </build>
  40. </project>
application.yaml
  1. spring:
  2. mail:
  3. host: smtp.qq.com #发送邮件服务器
  4. username: xxx@qq.com #QQ邮箱
  5. password: xxx #客户端授权码
  6. protocol: smtp #发送邮件协议
  7. properties.mail.smtp.auth: true
  8. properties.mail.smtp.port: 465 #端口号465或587
  9. properties.mail.display.sendmail: aaa #可以任意
  10. properties.mail.display.sendname: bbb #可以任意
  11. properties.mail.smtp.starttls.enable: true
  12. properties.mail.smtp.starttls.required: true
  13. properties.mail.smtp.ssl.enable: true #开启SSL
  14. default-encoding: utf-8
  15. freemarker:
  16. cache: false # 缓存配置 开发阶段应该配置为false 因为经常会改
  17. suffix: .html # 模版后缀名 默认为ftl
  18. charset: UTF-8 # 文件编码
  19. template-loader-path: classpath:/templates/ # 存放模板的文件夹,以resource文件夹为相对路径
  20. my:
  21. toemail: xx@xx.com
MailService.java
  1. package fun.seolas;
  2. import freemarker.template.Template;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.core.io.FileSystemResource;
  6. import org.springframework.mail.SimpleMailMessage;
  7. import org.springframework.mail.javamail.JavaMailSender;
  8. import org.springframework.mail.javamail.MimeMessageHelper;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
  11. import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
  12. import javax.annotation.Resource;
  13. import javax.mail.MessagingException;
  14. import javax.mail.internet.MimeMessage;
  15. import java.io.File;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. @Service
  19. public class MailService {
  20. // Spring官方提供的集成邮件服务的实现类,目前是Java后端发送邮件和集成邮件服务的主流工具。
  21. @Resource
  22. private JavaMailSender mailSender;
  23. @Autowired
  24. private FreeMarkerConfigurer freeMarkerConfigurer;
  25. // 从配置文件中注入发件人的姓名
  26. @Value("${spring.mail.username}")
  27. private String fromEmail;
  28. /**
  29. * 发送文本邮件
  30. *
  31. * @param to 收件人
  32. * @param subject 标题
  33. * @param content 正文
  34. */
  35. public void sendSimpleMail(String to, String subject, String content) {
  36. SimpleMailMessage message = new SimpleMailMessage();
  37. message.setFrom(fromEmail); // 发件人
  38. message.setTo(to);
  39. message.setSubject(subject);
  40. message.setText(content);
  41. mailSender.send(message);
  42. }
  43. /**
  44. * 发送html邮件
  45. */
  46. public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
  47. //注意这里使用的是MimeMessage
  48. MimeMessage message = mailSender.createMimeMessage();
  49. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  50. helper.setFrom(fromEmail);
  51. helper.setTo(to);
  52. helper.setSubject(subject);
  53. //第二个参数:格式是否为html
  54. helper.setText(content, true);
  55. mailSender.send(message);
  56. }
  57. /**
  58. * 发送freemarker邮件
  59. */
  60. public void sendTemplateMail(String to, String subject, String templatehtml) throws Exception {
  61. // 获得模板
  62. Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatehtml);
  63. // 使用Map作为数据模型,定义属性和值
  64. Map<String, Object> model = new HashMap<>();
  65. model.put("myname", "Seolas");
  66. // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串
  67. String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
  68. // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法
  69. this.sendHtmlMail(to, subject, templateHtml);
  70. }
  71. /**
  72. * 发送带附件的邮件
  73. */
  74. public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
  75. MimeMessage message = mailSender.createMimeMessage();
  76. //要带附件第二个参数设为true
  77. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  78. helper.setFrom(fromEmail);
  79. helper.setTo(to);
  80. helper.setSubject(subject);
  81. helper.setText(content, true);
  82. FileSystemResource file = new FileSystemResource(new File(filePath));
  83. String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  84. helper.addAttachment(fileName, file);
  85. mailSender.send(message);
  86. }
  87. }
MailTest.java
  1. package fun.seolas;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. import javax.mail.MessagingException;
  9. @SpringBootTest
  10. @RunWith(SpringRunner.class)
  11. public class MailTest {
  12. @Autowired
  13. private MailService mailService;
  14. @Value("${my.toemail}")
  15. private String toemail;
  16. @Test
  17. public void test01() {
  18. mailService.sendSimpleMail(toemail, "普通文本邮件", "普通文本邮件内容");
  19. }
  20. @Test
  21. public void test02() throws MessagingException {
  22. mailService.sendHtmlMail(toemail, "一封html测试邮件",
  23. "<div style=\"text-align: center;position: absolute;\" >\n"
  24. + "<h3>\"一封html测试邮件\"</h3>\n"
  25. + "<div>一封html测试邮件</div>\n"
  26. + "</div>");
  27. }
  28. @Test
  29. public void test3() throws Exception {
  30. mailService.sendTemplateMail(toemail, "基于模板的html邮件", "freemarkertemp.html");
  31. }
  32. @Test
  33. public void test04() throws MessagingException {
  34. String filePath = "C:\\Users\\Julia\\Downloads\\测试.txt";
  35. mailService.sendAttachmentsMail(toemail, "带附件的邮件", "邮件中有附件", filePath);
  36. }
  37. }

原文链接:https://www.cnblogs.com/seolas/p/17367494.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号