• SpringBoot实现发送邮件功能


            平时注册或者登录一个网站时,可能收到过邮件用来发送验证码等,邮件在项目中经常会被用到,比如邮件发送通知,比如通过邮件注册,认证,找回密码,系统报警通知,报表信息等。

    发送邮件用到了Spring Email的技术,我们这里使用的是SMTP

    1.邮箱打开SMTP服务

    找一个邮箱用来给其他邮箱发送文件,要用SMTP服务发送邮件,所以邮箱要提前开启这个功能。

    以163邮箱为例:(其他邮箱也是相同的操作)

    开启SMTP服务后,会出现弹框,将授权密码记录下来,注意:只出现一次

    还可以看到服务器地址 

    2.SpringBoot集成Email

    将下面的maven配置拷贝下来,集成到SpringBoot中。 

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-mailartifactId>
    4. <version>2.1.5.RELEASEversion>
    5. dependency>

    3.邮箱参数配置

    首先进行配置文件,配置文件的目的是告诉Spring需要用哪个邮箱来发送邮件

    写到SpringBoot的yaml配置文件里面

    (登录授权密码不是你邮箱的密码,是你邮箱开启SMTP服务后显示的那个授权密码)

    1. spring:
    2. mail:
    3. #邮箱域名、端口、邮箱账号、登录授权密码、启用smtps安全协议、采用ssl安全链接
    4. host: smtp.163.com
    5. port: 465
    6. username: ************@163.com
    7. password: ************
    8. protocol: smtps
    9. properties:
    10. mail.smtp.ssl.enable: true

    4.发送邮件工具类

    1. package com.kyw.util;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.beans.factory.annotation.Value;
    6. import org.springframework.mail.javamail.JavaMailSender;
    7. import org.springframework.mail.javamail.MimeMessageHelper;
    8. import org.springframework.stereotype.Component;
    9. import javax.mail.MessagingException;
    10. import javax.mail.internet.MimeMessage;
    11. @Component
    12. public class MailClient {
    13. private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
    14. @Autowired
    15. private JavaMailSender mailSender;
    16. //读取到配置类中的 “发送者”邮箱
    17. @Value("${spring.mail.username}")
    18. private String from;
    19. /**
    20. * 发送邮件
    21. * @param to “接收者”邮箱
    22. * @param subject 邮件的主题
    23. * @param content 邮件的内容
    24. */
    25. public void sendMail(String to, String subject, String content) {
    26. try {
    27. MimeMessage mimeMessage = mailSender.createMimeMessage();
    28. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
    29. helper.setFrom(from);
    30. helper.setTo(to);
    31. helper.setText(content,true);//表示可以发送HTML文件
    32. helper.setSubject(subject);
    33. mailSender.send(helper.getMimeMessage());
    34. } catch (MessagingException e) {
    35. logger.error("发送邮件失败:" + e.getMessage());
    36. }
    37. }
    38. }

    发送文本邮件测试

    写一个测试类来测试,给我的qq邮箱发送一个邮件

    1. package com.kyw;
    2. import com.kyw.util.MailClient;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.springframework.test.context.ContextConfiguration;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. @RunWith(SpringRunner.class)
    10. @SpringBootTest
    11. @ContextConfiguration(classes = SpringBootDemoApplication.class)
    12. public class MailTests {
    13. @Autowired
    14. private MailClient mailClient;
    15. @Test
    16. public void testTextMail() {
    17. mailClient.sendMail("2370553834@qq.com","TEST","测试,你好");
    18. }
    19. }

    收到啦

    发送HTML邮件

    也是用Thymeleaf实现的,没有配置Thymeleaf先去集成一下,搜索SpringBoot集成Thymeleaf即可。

    先写一个邮件模板页面,里面的username是动态的值,等待后端调用的时候填充

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>示例邮件title>
    6. head>
    7. <body>
    8. <table cellpadding="0" cellspacing="0" border="0" width="100%" bgcolor="#f2f2f2">
    9. <tr>
    10. <td align="center" style="padding: 20px 0;">
    11. <table cellpadding="0" cellspacing="0" border="0" width="600" bgcolor="#ffffff">
    12. <tr>
    13. <td align="center" style="padding: 20px 0;">
    14. <img src="https://pic.izihun.com/pic/art_font/2019/01/16/10/png_temp_1570533438378_9814.jpg?imageMogr2/auto-orient/thumbnail/820x/format/jpeg" alt="公司标志"width="150" height="150">
    15. td>
    16. tr>
    17. <tr>
    18. <td style="padding: 20px;">
    19. <h1>欢迎来到我们的邮件示例h1>
    20. <p>亲爱的收件人,<span th:text="${username}" >span> p>
    21. <p>这是一个示例邮件的内容。您可以在这里添加任何您想要的信息。p>
    22. <p>感谢您的阅读。p>
    23. <p>祝您一切顺利!p>
    24. td>
    25. tr>
    26. <tr>
    27. <td align="center" style="background-color: #f2f2f2; padding: 20px;">
    28. <a href="https://www.baidu.com" style="text-decoration: none; background-color: #007BFF; color: #ffffff; padding: 10px 20px; border-radius: 5px; font-weight: bold;">访问我们的网站a>
    29. td>
    30. tr>
    31. table>
    32. td>
    33. tr>
    34. table>
    35. body>
    36. html>

    后端测试类

    1. package com.kyw;
    2. import com.kyw.util.MailClient;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.springframework.test.context.ContextConfiguration;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. import org.thymeleaf.TemplateEngine;
    10. import org.thymeleaf.context.Context;
    11. @RunWith(SpringRunner.class)
    12. @SpringBootTest
    13. @ContextConfiguration(classes = SpringBootDemoApplication.class)
    14. public class MailTests {
    15. @Autowired
    16. private MailClient mailClient;
    17. /**
    18. *发送文本文件
    19. */
    20. @Test
    21. public void testTextMail() {
    22. mailClient.sendMail("2370553834@qq.com","TEST","测试,你好");
    23. }
    24. @Autowired
    25. private TemplateEngine templateEngine;
    26. /**
    27. *使用Thymeleaf 发送HTML邮件
    28. */
    29. @Test
    30. public void testHtmlMail() {
    31. Context context = new Context();
    32. context.setVariable("username","张三");
    33. String content = templateEngine.process("/mail/maildemo",context);
    34. System.out.println(content);
    35. mailClient.sendMail("2370553834@qq.com","TEST",content);
    36. }
    37. }

    注意路径要按照Thymeleaf的规范来

  • 相关阅读:
    实在是解决不了来提问一下。UE5,打开项目地变成黑色怎么解决?
    Redis 的6种回收策略(淘汰策略)详解
    HashMap为什么线程不安全?
    synchronized原理-字节码分析、对象内存结构、锁升级过程、Monitor
    「Verilog学习笔记」输入序列连续的序列检测
    Go Web——Gin简介
    python调用chrome实现网页自动操作
    LeetCode —— dfs和bfs
    算法金 | 突破最强算法模型!!学会随机森林,你也能发表高水平SCI
    基于模糊预测与扩展卡尔曼滤波的野值剔除方法
  • 原文地址:https://blog.csdn.net/KangYouWei6/article/details/132662094