当前位置:   article > 正文

spring boot学习第十一篇:发邮件

spring boot学习第十一篇:发邮件

1、pom.xml文件内容如下(是我所有学习内容需要的,不再单独分出来,包不会冲突):

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.6.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.hm-email</groupId>
  12. <artifactId>hm-email</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>hm-email</name>
  15. <description>hm-email</description>
  16. <properties>
  17. <java.version>8</java.version>
  18. <druid.version>1.2.8</druid.version>
  19. <log4jdbc.version>1.16</log4jdbc.version>
  20. <es.version>7.9.2</es.version>
  21. </properties>
  22. <dependencies>
  23. <!-- druid数据源驱动 -->
  24. <dependency>
  25. <groupId>com.alibaba</groupId>
  26. <artifactId>druid-spring-boot-starter</artifactId>
  27. <version>${druid.version}</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <!-- mybatis -->
  39. <dependency>
  40. <groupId>com.baomidou</groupId>
  41. <artifactId>mybatis-plus-boot-starter</artifactId>
  42. <version>3.5.3.1</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-starter-web</artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.projectlombok</groupId>
  54. <artifactId>lombok</artifactId>
  55. <optional>true</optional>
  56. </dependency>
  57. <!--Mysql依赖包-->
  58. <dependency>
  59. <groupId>mysql</groupId>
  60. <artifactId>mysql-connector-java</artifactId>
  61. <scope>runtime</scope>
  62. </dependency>
  63. <!--lombok插件-->
  64. <dependency>
  65. <groupId>org.projectlombok</groupId>
  66. <artifactId>lombok</artifactId>
  67. <optional>true</optional>
  68. </dependency>
  69. <!--监控sql日志-->
  70. <dependency>
  71. <groupId>org.bgee.log4jdbc-log4j2</groupId>
  72. <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
  73. <version>${log4jdbc.version}</version>
  74. </dependency>
  75. <dependency>
  76. <groupId>com.alibaba</groupId>
  77. <artifactId>fastjson</artifactId>
  78. <version>1.2.9</version>
  79. </dependency>
  80. <dependency>
  81. <groupId>redis.clients</groupId>
  82. <artifactId>jedis</artifactId>
  83. </dependency>
  84. <dependency>
  85. <groupId>org.apache.kafka</groupId>
  86. <artifactId>kafka-clients</artifactId>
  87. </dependency>
  88. <dependency>
  89. <groupId>org.springframework.kafka</groupId>
  90. <artifactId>spring-kafka</artifactId>
  91. </dependency>
  92. <!-- high client-->
  93. <dependency>
  94. <groupId>org.elasticsearch.client</groupId>
  95. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  96. <version>${es.version}</version>
  97. <exclusions>
  98. <exclusion>
  99. <groupId>org.elasticsearch</groupId>
  100. <artifactId>elasticsearch</artifactId>
  101. </exclusion>
  102. <exclusion>
  103. <groupId>org.elasticsearch.client</groupId>
  104. <artifactId>elasticsearch-rest-client</artifactId>
  105. </exclusion>
  106. </exclusions>
  107. </dependency>
  108. <!-- rest-high-level-client 依赖如下2个jar -->
  109. <dependency>
  110. <groupId>org.elasticsearch</groupId>
  111. <artifactId>elasticsearch</artifactId>
  112. <version>${es.version}</version>
  113. </dependency>
  114. <dependency>
  115. <groupId>org.elasticsearch.client</groupId>
  116. <artifactId>elasticsearch-rest-client</artifactId>
  117. <version>${es.version}</version>
  118. </dependency>
  119. <dependency>
  120. <groupId>junit</groupId>
  121. <artifactId>junit</artifactId>
  122. </dependency>
  123. <dependency>
  124. <groupId>org.springframework.boot</groupId>
  125. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  126. </dependency>
  127. <dependency>
  128. <groupId>org.springframework.boot</groupId>
  129. <artifactId>spring-boot-starter-security</artifactId>
  130. </dependency>
  131. <dependency>
  132. <groupId>org.springframework.security.oauth.boot</groupId>
  133. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  134. <version>2.4.0</version>
  135. </dependency>
  136. <dependency>
  137. <groupId>org.springframework.boot</groupId>
  138. <artifactId>spring-boot-starter-mail</artifactId>
  139. </dependency>
  140. <dependency>
  141. <groupId>org.springframework.boot</groupId>
  142. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  143. </dependency>
  144. </dependencies>
  145. <build>
  146. <plugins>
  147. <plugin>
  148. <groupId>org.springframework.boot</groupId>
  149. <artifactId>spring-boot-maven-plugin</artifactId>
  150. </plugin>
  151. </plugins>
  152. </build>
  153. </project>

2、application.yml内容如下:

  1. server:
  2. port: 8081
  3. servlet.context-path: /
  4. #配置数据源
  5. spring:
  6. datasource:
  7. druid:
  8. db-type: com.alibaba.druid.pool.DruidDataSource
  9. driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
  10. url: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
  11. username: ${DB_USER:root}
  12. password: ${DB_PWD:demo}
  13. redis:
  14. host: localhost
  15. port: 6379
  16. password: demo
  17. database: 10
  18. data:
  19. mongodb:
  20. host: 43.138.0.199
  21. port: 27017
  22. username: hmblogs
  23. password: demo
  24. database: hmblogs
  25. authentication-database: admin
  26. mail:
  27. host: smtp.163.com # smtp地址,开通的时候会显示
  28. username: southpoet@163.com # 你的邮箱账号
  29. password: demo # 你的邮箱授权码
  30. default-encoding: UTF-8
  31. properties:
  32. mail:
  33. smtp:
  34. socketFactory:
  35. class: javax.net.ssl.SSLSocketFactory
  36. auth: false
  37. starttls:
  38. enable: false
  39. debug: true
  40. protocol: smtp
  41. es:
  42. host: 43.138.0.199
  43. port: 9200
  44. scheme: http
  45. user: elastic
  46. password: demo

3、BackendApplication内容如下:

  1. package com.hmblogs.backend;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class BackendApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(BackendApplication.class, args);
  8. }
  9. }

4、EmailService文件内容如下:

  1. package com.hmblogs.backend.service;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.mail.SimpleMailMessage;
  6. import org.springframework.mail.javamail.JavaMailSender;
  7. import org.springframework.mail.javamail.MimeMessageHelper;
  8. import org.springframework.stereotype.Service;
  9. import javax.mail.MessagingException;
  10. import javax.mail.internet.MimeMessage;
  11. import java.io.File;
  12. @Service
  13. @Slf4j
  14. public class EmailService {
  15. @Autowired
  16. private JavaMailSender mailSender;
  17. @Value("${spring.mail.username}")
  18. private String username;
  19. /**
  20. * 使用thymeleaf模板
  21. * @param to
  22. * @param subject
  23. * @param context
  24. */
  25. public void sendHtmlMail(String to ,String subject,String context){
  26. try {
  27. MimeMessage mimeMessage = mailSender.createMimeMessage();
  28. MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
  29. mimeMessageHelper.setFrom(username);
  30. mimeMessageHelper.setTo(to);
  31. mimeMessageHelper.setText(context);
  32. mimeMessageHelper.setSubject(subject);
  33. mailSender.send(mimeMessage);
  34. } catch (MessagingException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. /**
  39. * 发送文本邮件
  40. *
  41. * @param to 收件人地址
  42. * @param subject 邮件主题
  43. * @param content 邮件内容
  44. * @param cc 抄送地址
  45. */
  46. public void sendSimpleMail(String to, String subject, String content, String... cc) {
  47. SimpleMailMessage message = new SimpleMailMessage();
  48. message.setFrom(username);
  49. message.setTo(to);
  50. message.setSubject(subject);
  51. message.setText(content);
  52. if (cc!=null) {
  53. message.setCc(cc);
  54. }
  55. mailSender.send(message);
  56. }
  57. /**
  58. * 发送带附件的邮件
  59. *
  60. * @param to 收件人地址
  61. * @param subject 邮件主题
  62. * @param content 邮件内容
  63. * @param filePath 附件地址
  64. * @param cc 抄送地址
  65. */
  66. public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) {
  67. try {
  68. MimeMessage message = mailSender.createMimeMessage();
  69. MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
  70. helper.setFrom(username);
  71. helper.setTo(to);
  72. helper.setSubject(subject);
  73. helper.setText(content, true);
  74. if (cc!=null) {
  75. helper.setCc(cc);
  76. }
  77. File file = new File(filePath);
  78. String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  79. helper.addAttachment(fileName, file);
  80. mailSender.send(message);
  81. } catch (MessagingException e) {
  82. log.error("发送邮件失败,收件人:{}", to, e);
  83. }
  84. }
  85. }

5、EmailServiceTest测试类内容如下:

  1. package com.hmblogs.backend.util;
  2. import com.hmblogs.backend.BackendApplication;
  3. import com.hmblogs.backend.service.EmailService;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import org.thymeleaf.TemplateEngine;
  10. import org.thymeleaf.context.Context;
  11. import javax.annotation.Resource;
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @SpringBootTest(classes={BackendApplication.class, EmailServiceTest.class})
  14. public class EmailServiceTest {
  15. @Resource
  16. private EmailService emailService;
  17. private static final String to = "southcxy@163.com";
  18. @Test
  19. public void test(){
  20. emailService.sendSimpleMail(to,"简单测试22","简单测试");
  21. }
  22. @Test
  23. public void testWithAttachment(){
  24. emailService.sendAttachmentsMail(to,"附件测试22","附件测试","E:\\fileTest.txt");
  25. }
  26. @Autowired
  27. TemplateEngine templateEngine;
  28. @Test
  29. public void sendHtmlMailThymeleaf(){
  30. Context context = new Context();
  31. context.setVariable("username","cyc");
  32. String mail = templateEngine.process("mailtemplate.html",context);
  33. emailService.sendHtmlMail(to,"恭喜22!",mail);
  34. }
  35. }

启动服务,执行该方法,报错如下:

  1. org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;
  2. nested exception is:
  3. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
  4. nested exception is:
  5. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  6. ; message exception details (1) are:
  7. Failed message 1:
  8. javax.mail.MessagingException: Could not convert socket to TLS;
  9. nested exception is:
  10. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  11. at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2140)
  12. at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:734)
  13. at javax.mail.Service.connect(Service.java:342)
  14. at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:518)
  15. at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:437)
  16. at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:323)
  17. at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:312)
  18. at com.hmblogs.backend.service.EmailService.sendSimpleMail(EmailService.java:42)
  19. at com.hmblogs.backend.util.EmailServiceTest.test(EmailServiceTest.java:21)
  20. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  21. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  22. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  23. at java.lang.reflect.Method.invoke(Method.java:498)
  24. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
  25. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  26. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
  27. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  28. at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
  29. at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
  30. at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
  31. at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
  32. at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
  33. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
  34. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
  35. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
  36. at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
  37. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
  38. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
  39. at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
  40. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
  41. at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  42. at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  43. at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
  44. at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
  45. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
  46. at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  47. at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
  48. at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
  49. at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
  50. at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
  51. at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
  52. at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
  53. Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  54. at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
  55. at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
  56. at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
  57. at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
  58. at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1514)
  59. at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
  60. at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
  61. at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
  62. at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
  63. at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
  64. at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
  65. at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
  66. at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:602)
  67. at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:529)
  68. at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2135)
  69. ... 41 more
  70. Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  71. at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
  72. at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
  73. at sun.security.validator.Validator.validate(Validator.java:260)
  74. at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
  75. at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
  76. at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
  77. at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
  78. ... 51 more
  79. Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  80. at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
  81. at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
  82. at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
  83. at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
  84. ... 57 more

查了一圈资料,和SSL证书有关的,都不行,最后试着改改配置文件,发现搞好了

目标邮箱收到了如下邮件:

发件邮箱,发的邮件如下:

但是,问题是,模板html没解析出来,非研发同学肯定看不懂邮件内容,

 怎么处理呢?

比对网上的资料,

问题解决了,邮件截图如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/86631
推荐阅读
相关标签
  

闽ICP备14008679号