整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

springboot(二十四)使用springboot发送邮件

面记录使用springboot发送四种邮件的方法:普通文本、html、附件、模板html

1、引入springboot依赖包

gradle:

 compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
 compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

maven:

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

spring-boot-starter-mail实现邮件发送
spring-boot-starter-thymeleaf实现模板的创建

2、 在resources/templates中创建一个模板html:emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>这是一个测试的模板</title>
</head>
<body>
您的账号存在异常,请点击下面链接进行安全验证<br/>
<a href="#" th:href="@{http://www.lalalala.com/{userid}(userid=${userid})}">安全验证</a>
</body>
</html>

3、 四种邮件发送测试代码

package com.iscas.biz.test.controller;

import com.iscas.templet.common.BaseController;
import com.iscas.templet.common.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送测试
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:16
 * @since jdk1.8
 */
@RestController
@RequestMapping("/send/email/test")
@Slf4j
public class SendEmailController extends BaseController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 测试发送普通文本邮件
     * */
    @GetMapping("/text")
    public ResponseEntity testText() {

        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人地址
        message.setFrom("461402005@qq.com");
        // 收件人地址
        message.setTo("76775081@qq.com");
        // 邮件标题
        message.setSubject("这是一个测试");
        // 邮件正文
        message.setText("这是测试正文");

        javaMailSender.send(message);
        log.debug("发送成功!");

        return getResponse();
    }

    /**
     * 测试发送HTML邮件
     * */
    @GetMapping("/html")
    public ResponseEntity testHtml() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是html测试");
        // 发送HTML邮件
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }

    /**
     * 测试发送附件
     * */
    @GetMapping("/attachment")
    public ResponseEntity testAttachment() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是附件测试");
        // 发送HTML
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        helper.setText(html, true);

        //发送附件
        FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
        // 发送文件名
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }

    /**
     * 测试发送thymeleaf模板邮件
     * */
    @GetMapping("/template")
    public ResponseEntity testTemplate() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是模板测试");

        //获取模板生成html
        Context context = new Context();
        // 这里的id与resources/templates下的模板文件中的${userid}必须对应
        context.setVariable("userid", 1);
        // 这里的"emailTemplate"与resources/templates下的模板文件一直
        String html = templateEngine.process("emailTemplate", context);
        helper.setText(html, true);

        //发送附件
        FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
        // 发送文件名
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }
}

4、 将邮件发送封装为工具类

package com.iscas.base.biz.service.common;

import cn.hutool.core.io.IoUtil;
import com.iscas.templet.common.ResponseEntity;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 发送邮件工具
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:52
 * @since jdk1.8
 */
@Service
@Slf4j
public class SendEmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送普通文本邮件
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param content 邮件正文文本
     * */
    public void sendText(String from, String to, String title, String content) {


        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人地址
        message.setFrom(from);
        // 收件人地址
        message.setTo(to);
        // 邮件标题
        message.setSubject(title);
        // 邮件正文
        message.setText(content);

        javaMailSender.send(message);
        log.debug("邮件发送成功!");
    }

    /**
     * 发送HTML邮件
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param html 邮件正文html
     * */
    public void sendHtml(String from, String to, String title, String html) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);
        // 发送HTML邮件
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("邮件发送成功");

    }

    /**
     * 发送附件
     *
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param html 邮件正文html
     * @param inputStream 附件输入流
     * @param fileName 文件名称
     *
     * */
    public void sendAttachment(String from, String to, String title, String html, InputStream inputStream, String fileName) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);
        // 发送HTML
        helper.setText(html, true);

        //发送附件

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.copy(inputStream, baos);

        ByteArrayResource byteArrayResource = new ByteArrayResource(baos.toByteArray());
        // 发送文件名
        helper.addAttachment(fileName, byteArrayResource);

        javaMailSender.send(message);
        log.debug("发送成功");

    }

    /**
     * 测试发送thymeleaf模板邮件
     * templateName必须在resources/templates下
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param templateName 模板名称,templateName必须在resources/templates下
     * @param context 构建模板的上下文,构建方式参见单元测试
     * */
    @GetMapping("/template")
    public void sendTemplate(String from, String to, String title, String templateName, Context context) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);

        //获取模板生成html
        String html = templateEngine.process(templateName, context);
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("邮件发送成功");

    }

    /**
     * 测试发送thymeleaf模板邮件,并携带附件
     * templateName必须在resources/templates下
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param templateName 模板名称,templateName必须在resources/templates下
     * @param context 构建模板的上下文,构建方式参见单元测试
     * @param inputStream 附件输入流
     * @param fileName 文件名称
     * */
    public void sendTemplateWithAttachment(String from, String to, String title, String templateName, Context context, InputStream inputStream, String fileName) throws MessagingException {
        //获取模板生成html
        String html = templateEngine.process(templateName, context);
        sendAttachment(from, to, title, html, inputStream, fileName);
    }
}

5、单元测试 


子邮件服务器

电子邮件服务器类比于现实中的邮局。用户发邮件时,会将邮件发送到邮件服务器,邮件服务器将邮件再发送到接收方的电子邮箱中。

邮件服务器又可以分为两种类型:

“SMTP邮件服务器:替用户发送邮件和接收外面发送给本地用户的邮件。POP3/IMAP邮件服务器:帮助用户读取SMTP邮件服务器接收进来的邮件。”

邮件传输协议

邮件传输协议有如下几种

  • SMTP协议:全称为 Simple Mail Transfer Protocol,简单邮件传输协议。它定义了邮件客户端软件和SMTP邮件服务器之间,以及两台SMTP邮件服务器之间的通信规则。
  • POP3协议:全称为 Post Office Protocol,邮局协议。它定义了邮件客户端软件和POP3邮件服务器的通信规则。
  • IMAP协议:全称为 Internet Message Access Protocol,Internet消息访问协议,它是对POP3协议的一种扩展,也是定义了邮件客户端软件和IMAP邮件服务器的通信规则。

邮箱开启SMTP/IMAP服务

以QQ邮箱为例

开启后需要生成授权码。

我为什么选择SpringBoot框架来发送邮件

我们来看看纯Java代码发邮件。

send方法就如此之长,而SpringBoot将发送功能封装好了。接下来你将看到用SpringBoot发送邮件是如何的简单。

SpringBoot发送邮

导入Maven jar包

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

<!--模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

这里的模板引擎后面需要,这里先导入进来。

application.properties文件配置

#邮件配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=1587xx3453@qq.com
spring.mail.password=yurzjzmreurpgfdghalouke
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

如果是QQ邮箱发送,你只需要修改username和password。password为上面生成的授权码,不是你邮箱的登录密码哦。

编写邮件发送方法

发送结果

如果我们要发送附件

发送结果如下图

如果需要在正文插入图片

发送结果如下

当然我们也可以使用模板引擎

在resources/templates目录下创建文件thymeleaf-mail.html文件。

thymeleaf-mail.html内容如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>嗨!欢迎关注我的博客:Lvshen的技术小屋:</p>
<table border="1">
    <tr>
        <td>姓名</td>
        <td th:text="${username}"></td>
    </tr>
    <tr>
        <td>性别</td>
        <td th:text="${sex}"></td>
    </tr>
    <tr>
        <td>爱好</td>
        <td th:text="${hobby}"></td>
    </tr>
</table>
<div style="color: #ff1a0e">关注我获取Java学习资料哦</div>
</body>
</html>

编写发送代码

测试结果如下

如果你没有开发过邮件发送或正在开发邮件发送的功能,希望这篇文章可以帮到你。

、要使用JavaMailSender发送邮件,首先需要在pom.xml文件中引入spring-boot-starter-mail依赖:

spring-boot-starter-mail依赖

2、引入依赖包后需要在application.properties文件中配置属性:

属性配置

password为客户端授权码,而不是我们平常登录邮箱的密码,我这里使用的是163邮箱作为发送方(客户端授权码需要进入邮箱里面设置获取,这里就不介绍了)。

3、引入依赖包,写好配置文件后,接下来就是写业务代码了,代码很简单,想要深究原理就得去阅读源码了,这里只介绍如何实现,废话不多说,业务代码如下:(截图无法显示,只能贴代码了)

@Service

public class MailService {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired

private JavaMailSender sender;

//发送者

@Value("${spring.mail.username}")

private String from;

/**

* 发送纯文本的简单邮件

* @param sendTo 接收者

* @param Subject 邮件主题

* @param mailContent 邮件内容

* @return

*/

public String sendSimpleMail(String sendTo, String Subject, String mailContent){

//建立邮件消息

SimpleMailMessage message = new SimpleMailMessage();

message.setFrom(from);

message.setTo(sendTo);

message.setSubject(Subject);

message.setText(mailContent);

try {

sender.send(message);

logger.info("");

} catch (Exception e) {

logger.error("发送简单邮件时发生异常!", e);

}

return "";

}

/**

* 发送HTML格式邮件

* @param sendTo

* @param Subject

* @param mailContent

*/

public void sendHtmlMail(String sendTo, String Subject, String mailContent){

MimeMessage message = sender.createMimeMessage();

try {

//true表示需要创建一个multipart message

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);

helper.setTo(sendTo);

helper.setSubject(Subject);

//HTML格式邮件需先进行Base64加密,取数据时再解码

helper.setText(mailContent, true);

sender.send(message);

logger.info("HTML邮件已经发送。");

} catch (MessagingException e) {

logger.error("发送HTML邮件时发生异常!", e);

}

}

/**

* 带附件的邮件

* @param sendTo

* @param Subject

* @param mailContent

* @param filePath

*/

public void sendAttachmentsMail(String sendTo, String Subject, String mailContent, String filePath){

MimeMessage message = sender.createMimeMessage();

try {

//true表示需要创建一个multipart message

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);

helper.setTo(sendTo);

helper.setSubject(Subject);

helper.setText(mailContent, true);

FileSystemResource file = new FileSystemResource(new File(filePath));

String fileName = filePath.substring(filePath.lastIndexOf(File.separator));

helper.addAttachment(fileName, file);

sender.send(message);

logger.info("带附件的邮件已经发送。");

} catch (MessagingException e) {

logger.error("发送带附件的邮件时发生异常!", e);

}

}

/**

* 发送带图片(静态资源)的邮件

* @param sendTo

* @param Subject

* @param mailContent 邮件内容,需要包含一个静态资源的id

* @param rscPath 静态资源路径和文件名

* @param rscId 静态资源id

*/

public void sendInlineResourceMail(String sendTo, String Subject, String mailContent, String rscPath, String rscId){

MimeMessage message = sender.createMimeMessage();

try {

//true表示需要创建一个multipart message

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);

helper.setTo(sendTo);

helper.setSubject(Subject);

helper.setText(mailContent, true);

FileSystemResource res = new FileSystemResource(new File(rscPath));

helper.addInline(rscId, res);

sender.send(message);

logger.info("带图片的邮件已经发送。");

} catch (MessagingException e) {

logger.error("发送带图片的邮件时发生异常!", e);

}

}

}

4、写完业务代码就可以写测试代码进行测试了,我是写了个controller进行调用,用Junit也可以,方式不限,测试代码如下下

@RestController

@RequestMapping("/mail")

public class MailController {

@Autowired

private MailService mailService;

@RequestMapping("/sendmail")

public String sendMail(){

//接收者邮箱(随意什么邮箱)

String to = "123456@qq.com";

return mailService.sendSimpleMail(to, "主题:测试发送邮件功能", "测试发送邮件功能");

}

}

到了这里,在浏览器地址栏输入127.0.0.1:8080/mail/sendmail并回车,邮件便可以发送成功了。