• 使用Spring Boot向邮箱发送邮件


    1.引入依赖

    在pom文件中引入以下jar包依赖。

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-mailartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    2.邮箱配置信息

    在Spring Boot配置文件application.yml中配置邮箱信息;当然邮箱发送人不确定的话,可以通过数据库中创建邮箱配置表来进行存储,这里就不多做介绍了。

    server:
      port: 8080
    spring:
      mail:
      	# 邮件服务地址,可以配置其他邮箱服务地址,例如:smtp.qq.com
        host: smtp.163.com
        username: 你的邮箱账号
        password: 你的邮箱密码
        properties:
          mail:
            smtp:
              auth: true
              #如果是用 SSL 方式,需要配置如下属性
              starttls:
                enable: true
                required: true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    3.编写测试类实现发送简单的邮件

    编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人,这里不是在yml配置的邮箱发送人信息的话,可以在业务层逻辑中通过数据库查询。

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/email")
    public class EmailTestController {
    
        @Autowired
        private JavaMailSender jms;
        
        @Value("${spring.mail.username}")
        private String from;
        
        @RequestMapping("sendSimpleTestEmail")
        public String sendSimpleTestEmail() {
            try {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(from);
                message.setTo("123456789@qq.com"); // 接收地址
                message.setSubject("一封简单的测试邮件"); // 标题
                message.setText("使用Spring Boot发送测试邮件。"); // 内容
                jms.send(message);
                return "发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    4.编写测试类实现发送HTML格式的邮件

    编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。

    import javax.mail.internet.MimeMessage;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/email")
    public class EmailTestController{
    
        @Autowired
        private JavaMailSender jms;
        
        @Value("${spring.mail.username}")
        private String from;
        
        @RequestMapping("sendHtmlTestEmail")
        public String sendHtmlTestEmail() {
            MimeMessage message = null;
            try {
                message = jms.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from); 
                helper.setTo("123456789@qq.com"); // 接收地址
                helper.setSubject("一封HTML格式的邮件"); // 标题
                // 带HTML格式的内容
                StringBuffer sb = new StringBuffer("

    使用Spring Boot发送HTML格式邮件。

    "
    ); helper.setText(sb.toString(), true);//true表示发送HTML格式邮件 jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    5.编写测试类实现发送带附件格式的邮件

    编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。

    import java.io.File;
    
    import javax.mail.internet.MimeMessage;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/email")
    public class EmailTestController{
    
        @Autowired
        private JavaMailSender jms;
        
        @Value("${spring.mail.username}")
        private String from;
    	
        @RequestMapping("sendAttachmentsTestMail")
        public String sendAttachmentsTestMail() {
            MimeMessage message = null;
            try {
                message = jms.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from); 
                helper.setTo("123456789@qq.com"); // 接收地址
                helper.setSubject("一封带附件的邮件"); // 标题
                helper.setText("详情参见附件内容!"); // 内容
                // 传入附件
                FileSystemResource file = new FileSystemResource(new File("file/项目文档.docx"));//附件相对路径
                helper.addAttachment("项目文档.docx", file);//添加附件到对象中
                jms.send(message);
                return "发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    6.编写测试类实现发送带静态资源的邮件

    编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人。发送带静态资源的邮件其实就是在发送HTML邮件的基础上嵌入静态资源(比如图片),嵌入静态资源的过程和传入附件类似,唯一的区别在于需要标识资源的cid:

    import java.io.File;
    
    import javax.mail.internet.MimeMessage;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/email")
    public class EmailTestController{
    
        @Autowired
        private JavaMailSender jms;
        
        @Value("${spring.mail.username}")
        private String from;
    	
        @RequestMapping("sendInlineTestMail")
        public String sendInlineTestMail() {
            MimeMessage message = null;
            try {
                message = jms.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from); 
                helper.setTo("123456789@qq.com"); // 接收地址
                helper.setSubject("一封带静态资源的邮件"); // 标题
                helper.setText("图片:", true); // 内容
                // 传入附件
                FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
                helper.addInline("img", file); //img和图片标签里cid后的名称相对应
                jms.send(message);
                return "发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    7.编写测试类实现使用模板发送邮件

    编写EmailTestController,注入JavaMailSender对象,注入配置文件中发送人在发送验证码等情况下可以创建一个邮件的模板,唯一的变量为验证码。这个例子中使用的模板解析引擎为Thymeleaf,所以首先引入Thymeleaf依赖:

    >
        >org.springframework.boot>
        >spring-boot-starter-thymeleaf>
    >
    
    • 1
    • 2
    • 3
    • 4

    在template目录下创建一个emailTemplate.html模板:

    DOCTYPE html>
    <html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>模板title>
    head>
    
    <body>
        您的验证码为{code},该验证码有效期为60秒。
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    发送模板邮件,本质上还是发送HTML邮件,只不过多了绑定变量的过程。

    import java.io.File;
    
    import javax.mail.internet.MimeMessage;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    @RestController
    @RequestMapping("/email")
    public class EmailTestController{
    
        @Autowired
        private JavaMailSender jms;
        
        @Value("${spring.mail.username}")
        private String from;
        
        @Autowired
        private TemplateEngine templateEngine;
    	
        @RequestMapping("sendTemplateTestEmail")
        public String sendTemplateTestEmail(String code) {
            MimeMessage message = null;
            try {
                message = jms.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from); 
                helper.setTo("123456789@qq.com"); // 接收地址
                helper.setSubject("邮件摸板测试"); // 标题
                // 处理邮件模板
                Context context = new Context();
                context.setVariable("code", code);
                String template = templateEngine.process("emailTemplate", context);
                helper.setText(template, true);
                jms.send(message);
                return "发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
  • 相关阅读:
    Windows安装MySQL详细教程
    【摸鱼神器】UI库秒变LowCode工具——列表篇(二)维护json的小工具
    常用颜色的英文和十六进制
    Acwing双指针算法
    MySQL - DCL(数据控制语言)介绍
    使用Torchmetrics快速进行验证指标的计算
    STM32 USB CDC 虚拟串口
    2007-2022 年上市公司国内外专利授权情况数据
    如何靠掌握自己的大数据打破信息流的壁垒?
    Python学习之路-爬虫提高:selenium
  • 原文地址:https://blog.csdn.net/lihaoyiding/article/details/125895366