首页 > 其他分享 >SpringBoot 整合邮件发送

SpringBoot 整合邮件发送

时间:2022-10-10 10:46:59浏览次数:81  
标签:SpringBoot helper mail springframework 发送 org import 邮件

邮件发送

更多参考:

https://mrbird.cc/Spring-Boot-Email.html

引入依赖

在Spring Boot中发送邮件,需要用到spring-boot-starter-mail,引入spring-boot-starter-mail

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

邮件配置

在application.yml中进行简单的配置(以QQ邮件为例):

server:
  port: 80

spring:
  mail:
#mtp服务主机  qq邮箱则为smtp.qq.com;163邮箱是smtp.163.com
    host: smtp.qq.com
    #服务协议
    protocol: smtp
    default-encoding: UTF-8
    username: [email protected]
    password: enxspdgxtrwugaif
    test-connection: true
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

spring.mail.username 邮箱

spring.mail.password 密钥,授权码


  • 授权码打开

image-20221010101805869

发送简单的邮件

编写EmailController,注入JavaMailSender:

      //	引入邮件接口
    @Resource
    private JavaMailSender javaMailSender;

    //	获得发件人信息
    @Value("${spring.mail.username}")
    private String emailName;
    //    邮箱验证码
    static String emailAuth;


    @PostMapping("regCaptcha")
    public Object captcha(@RequestParam String email) {
//        TODO 生产验证码 hutool
        emailAuth = String.valueOf(new Random().nextInt(899999) + 100000);
        try {
            sendAttachmentsMail(emailAuth,email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok("发送成功");
    }


    public void sendAttachmentsMail(String emailAuth,String email){
        //        创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(emailName);

        message.setTo(email);

        message.setSubject("[mall]@rain-me验证码是");

        message.setText("尊敬的"+email+",您好:\n"
                + "\n本次请求的邮件验证码为:" + emailAuth + ",本验证码 5 分钟内效,请及时输入。(请勿泄露此验证码)\n"
                + "\n如非本人操作,请忽略该邮件。\n(这是一封通过自动发送的邮件,请不要直接回复)");

        javaMailSender.send(message);
    }

启动项目访问http://localhost/email/sendSimpleEmail,提示发送成功:


image-20221010102314455

发送HTML格式的邮件

改造EmailControllerSimpleMailMessage替换为MimeMessage

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 EmailController {

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @RequestMapping("sendHtmlEmail")
    public String sendHtmlEmail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("[email protected]"); // 接收地址
            helper.setSubject("一封HTML格式的邮件"); // 标题
            // 带HTML格式的内容
            StringBuffer sb = new StringBuffer("<p style='color:#6db33f'>使用Spring Boot发送HTML格式邮件。</p>");
            helper.setText(sb.toString(), true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

helper.setText(sb.toString(), true);中的true表示发送HTML格式邮件。启动项目,访问http://localhost/email/sendHtmlEmail,提示发送成功,可看到文本已经加上了颜色#6db33f

QQ截图20180509112837.png

发送带附件的邮件

发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。不过使用的仍是MimeMessage

package com.springboot.demo.controller;

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 EmailController {

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
	
    @RequestMapping("sendAttachmentsMail")
    public String sendAttachmentsMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("[email protected]"); // 接收地址
            helper.setSubject("一封带附件的邮件"); // 标题
            helper.setText("详情参见附件内容!"); // 内容
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/项目文档.docx"));
            helper.addAttachment("项目文档.docx", file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

启动项目访问http://localhost/email/sendAttachmentsMail,提示发送成功:

QQ截图20180510101405.png

发送带静态资源的邮件

发送带静态资源的邮件其实就是在发送HTML邮件的基础上嵌入静态资源(比如图片),嵌入静态资源的过程和传入附件类似,唯一的区别在于需要标识资源的cid:

package com.springboot.demo.controller;

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 EmailController {

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
	
    @RequestMapping("sendInlineMail")
    public String sendInlineMail() {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("[email protected]"); // 接收地址
            helper.setSubject("一封带静态资源的邮件"); // 标题
            helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容
            // 传入附件
            FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
            helper.addInline("img", file); 
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

helper.addInline("img", file);中的img和图片标签里cid后的名称相对应。启动项目访问http://localhost/email/sendInlineMail,提示发送成功:

QQ截图20180510111000.png



使用模板发送邮件

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

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

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>模板</title>
</head>

<body>
    您好,您的验证码为{code},请在两分钟内使用完成操作。
</body>
</html>

发送模板邮件,本质上还是发送HTML邮件,只不过多了绑定变量的过程,详细如下所示:

package com.springboot.demo.controller;

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 EmailController {

    @Autowired
    private JavaMailSender jms;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Autowired
    private TemplateEngine templateEngine;
	
    @RequestMapping("sendTemplateEmail")
    public String sendTemplateEmail(String code) {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); 
            helper.setTo("[email protected]"); // 接收地址
            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();
        }
    }
}

其中code对应模板里的${code}变量。启动项目,访问http://localhost/email/sendTemplateEmail?code=EOS9,页面提示发送成功:

QQ截图20180510134244.png

标签:SpringBoot,helper,mail,springframework,发送,org,import,邮件
From: https://www.cnblogs.com/rain-me/p/16774779.html

相关文章

  • python解决urllib发送请求报错:urllib.error.URLError: <urlopen error [SSL: CERTIFIC
    在使用urllib.request.Request(url)前,添加代码放到最前面importssl ssl._create_default_https_context=ssl._create_unverified_context问题缘由:因为访问的网站是htt......
  • Java开发学习(三十七)----SpringBoot多环境配置及配置文件分类
    一、多环境配置在工作中,对于开发环境、测试环境、生产环境的配置肯定都不相同,比如我们开发阶段会在自己的电脑上安装mysql,连接自己电脑上的mysql即可,但是项目开发完毕......
  • Centos7使用sendEmail-v1.56发送邮件
    Centos7使用sendEmail-v1.56发送邮件注意:Centos7默认使用perl5.16,而sendEmail-v.1.56要求使用perl5.10。否则会报以下错误。所以需要下载并安装Perl-5.10Usingthedefa......
  • shell 企业微信机器人发送消息
    目录shell企业微信机器人发送消息企业微信群创建机器人实例shell企业微信机器人发送消息企业微信群创建机器人创建完机器人后我们会获取到一个webhook,通过curl调用we......
  • springboot整合mybatisPlus
    引入场景启动器              ......
  • Springboot日志记录方案
    目录​​一、概述​​​​二、市面上的日志框架以及日志抽象层类​​​​三、slf4j+Logback​​​​第一种:简单配置​​​​第二种:通过logback专有的xml配置文件详细配置​......
  • Springboot中tomcat配置、三大组件配置、拦截器配置
    1.tomcat配置Springboot默认使用的就是嵌入式servlet容器即tomcat,对于web项目,如果使用的是外部tomcat,相关配置比如访问端口、资源路径等可以在tomcat的conf文件下配置。但是......
  • Springboot整合JPA
      概述前面文章记录了Springboot整合Mybatis以及Spingboot整合JDBCTemlate的过程,这篇文章记录Springboot整合JPA操作过程。jpa实际也是用来操作数据库的持久层框架,如何使......
  • Springboot异常处理和自定义错误页面及@ControllerAdvice 注解的三种使用场景!五、@Con
    一、前言springboot默认发生4xx错误时候,pc端响应的页面如下如果是移动端(手机端)将会响应json格式的数据,如下二、Springboot异常处理为什么我们请求错误的路径,boot会给我们返......
  • Springboot整合jsp
    1.创建项目2.选择war工程3.这里可以选择web模块引入(我这里选择的boot版本是2.2.1)4.必须要引入的依赖<dependency><groupId>org.apache.tomcat.embed</groupId><artifa......