springboot2.0图文教程|集成邮件发送功能

犬小哈      2022-05-02     815

关键词:

技术图片

文章首发自个人微信公众号: 小哈学Java
个人网站: https://www.exception.site/springboot/spring-boots-send-mail

大家好,后续会间断地奉上一些 Spring Boot 2.x 相关的博文,包括 Spring Boot 2.x 教程和 Spring Boot 2.x 新特性教程相关,如 WebFlux 等。还有自定义 Starter 组件的进阶教程,比如:如何封装一个自定义图床 Starter 启动器(支持上传到服务器内部,阿里 OSS 和七牛云等), 仅仅需要配置相关参数,就可以将图片上传功能集成到现有的项目中。

好吧,这些都是后话。今天主要来讲讲如何在 Spring Boot 2.x 版本中集成发送邮件功能。

可以说,邮件发送在企业级应用中是比较常见的服务了,如运维报警,用户激活,广告推广等场景,均会使用到它。废话少说,开干!

目录

一、添加依赖

二、添加邮件相关配置

三、关于授权码

  • 3.1 什么是 QQ 邮箱授权码
  • 3.2 如何获取

四、开始编码

  • 4.1 定义功能类
  • 4.2 项目结构
  • 4.3 单元测试,验证效果

五、总结

六、GitHub 源码地址

一、添加依赖

pom.xml 文件中添加 spring-boot-starter-mail 依赖:

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

二、添加邮件相关配置

application.properties 配置文件中添加下面内容:

# 发送邮件的服务器,笔者这里使用的 QQ 邮件
spring.mail.host=smtp.qq.com
spring.mail.username=你的邮箱地址
spring.mail.password=授权码,或邮箱密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

yml 格式的配置文件,添加如下:

spring:
  mail:
    host: smtp.qq.com #发送邮件的服务器,笔者这里使用的 QQ 邮件
    username: 你的邮箱地址
    password: 授权码,或邮箱密码
    properties.mail.smtp.auth: true
    properties.mail.smtp.starttls.enable: true
    default-encoding: utf-8

三、关于授权码

对于上面的配置,您肯定对密码配置那块还抱有疑问,如果您使用的是 163 邮箱,或者 Gmail 邮箱,直接使用密码就可以了,如果您使用的是 QQ 邮箱,则需要先获取授权码。

到底什么事授权码? :

3.1 什么是 QQ 邮箱授权码

下图截自 QQ 邮箱官方文档:

技术图片

3.2 如何获取

登录 QQ 邮箱:

技术图片

点击设置:

技术图片

跳转页面后,点击账户,将页面往下拖动,您会看到:

技术图片

验证成功过后,即可获取授权码:

技术图片

四、开始编码

4.1 定义功能类

先定义一个邮件服务的接口类, MailService.java:

package site.exception.springbootmail.service;

/**
 * @author 犬小哈(微信号: 小哈学Java)
 * @site 个人网站: www.exception.site
 * @date 2019/4/10
 * @time 下午4:19
 * @discription
 **/
public interface MailService {

    /**
     * 发送简单文本的邮件
     * @param to
     * @param subject
     * @param content
     * @return
     */
    boolean send(String to, String subject, String content);

    /**
     * 发送 html 的邮件
     * @param to
     * @param subject
     * @param html
     * @return
     */
    boolean sendWithHtml(String to, String subject, String html);

    /**
     * 发送带有图片的 html 的邮件
     * @param to
     * @param subject
     * @param html
     * @param cids
     * @param filePaths
     * @return
     */
    boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths);


    /**
     * 发送带有附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePaths
     * @return
     */
    boolean sendWithWithEnclosure(String to, String subject, String content, String[] filePaths);

}

接口内定义了四个方法:

  1. send(): 发送简单文本的邮件;
  2. sendWithHtml(): 发送 html 的邮件;
  3. sendWithImageHtml(): 发送带有图片的 html 的邮件;
  4. sendWithWithEnclosure: 发送带有附件的邮件;

完成接口的定义以后,我们再定义一个具体实现类,MailServiceImpl.java:

package site.exception.springbootmail.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
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.stereotype.Service;
import org.springframework.util.Assert;
import site.exception.springbootmail.service.MailService;

import javax.mail.internet.MimeMessage;

/**
 * @author 犬小哈(微信号: 小哈学Java)
 * @site 个人网站: www.exception.site
 * @date 2019/4/10
 * @time 下午4:19
 * @discription
 **/
@Service
public class MailServiceImpl implements MailService {

    private final static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单文本的邮件
     * @param to
     * @param subject
     * @param content
     * @return
     */
    @Override
    public boolean send(String to, String subject, String content) {
        logger.info("## Ready to send mail ...");

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 邮件发送来源
        simpleMailMessage.setFrom(mailProperties.getUsername());
        // 邮件发送目标
        simpleMailMessage.setTo(to);
        // 设置标题
        simpleMailMessage.setSubject(subject);
        // 设置内容
        simpleMailMessage.setText(content);

        try {
            // 发送
            javaMailSender.send(simpleMailMessage);
            logger.info("## Send the mail success ...");
        } catch (Exception e) {
            logger.error("Send mail error: ", e);
            return false;
        }

        return true;
    }

    /**
     * 发送 html 的邮件
     * @param to
     * @param subject
     * @param html
     * @return
     */
    @Override
    public boolean sendWithHtml(String to, String subject, String html) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容,并设置内容 html 格式为 true
            mimeMessageHelper.setText(html, true);

            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with html success ...");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Send html mail error: ", e);
            return false;
        }

        return true;
    }

    /**
     * 发送带有图片的 html 的邮件
     * @param to
     * @param subject
     * @param html
     * @param cids
     * @param filePaths
     * @return
     */
    @Override
    public boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容,并设置内容 html 格式为 true
            mimeMessageHelper.setText(html, true);

            // 设置 html 中内联的图片
            for (int i = 0; i < cids.length; i++) {
                FileSystemResource file = new FileSystemResource(filePaths[i]);
                // addInline() 方法 cid 需要 html 中的 cid (Content ID) 对应,才能设置图片成功,
                // 具体可以参见,下面 4.3.3 单元测试的参数设置
                mimeMessageHelper.addInline(cids[i], file);
            }

            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with image success ...");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Send html mail error: ", e);
            return false;
        }

        return true;
    }

    /**
     * 发送带有附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePaths
     * @return
     */
    @Override
    public boolean sendWithWithEnclosure(String to, String subject, String content, String[] filePaths) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容
            mimeMessageHelper.setText(content);

            // 添加附件
            for (int i = 0; i < filePaths.length; i++) {
                FileSystemResource file = new FileSystemResource(filePaths[i]);
                String attachementFileName = "附件" + (i + 1);
                mimeMessageHelper.addAttachment(attachementFileName, file);
            }

            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with enclosure success ...");
        } catch (Exception e) {
            logger.error("Send html mail error: ", e);
            return false;
        }
        return true;
    }
}

4.2 项目结构

完成上面功能类的编码后,看下项目结构如下:

技术图片

4.3 单元测试,验证效果

4.3.1 简单文本发送

技术图片

填写相关测试参数,包括目标邮箱地址,标题,内容,运行单元测试:

技术图片

单元测试通过,再看下实际效果:

技术图片

邮件正常发送。

4.3.2 发送 Html

技术图片

填写相关测试参数,包括目标邮箱地址,标题,html 内容,运行单元测试通过,直接看效果:

技术图片

可以看到,邮件发送成功!

4.3.3 发送带有图片的 Html

技术图片

填写相关测试参数,包括目标邮箱地址,标题,html 内容,html 中包含了两张图片,并且 src 中的内容是 cid:{flag}的格式,前缀 cid:是固定的,您需要改变是后面的标志位,通过 addInline(cid, file) 来将 cid 和具体的图片文件对应起来。

运行单元测试通过,看看效果如何:

技术图片

可以看到 html 中图片也是 OK 的。

PS: 这里笔者在测试发送给 QQ 邮箱的时候,图片显示不成功,暂时还没找到问题在哪,如果有哪位读者知道,不妨后台发个消息告诉一下笔者哈。

4.3.4 发送带有附件的邮件

技术图片填写相关测试参数,包括目标邮箱地址,标题,内容,并添加了两个附件,运行单元测试,看看实际效果:

技术图片

发送成功,到此所有的单元测试全部运行通过。

五、总结

本文中,我们学习如何在 Spring Boot 2.x 版本中集成发送邮件功能,包括发送简单文本,Html 内容,带有图片的 Html 内容,以及带有的附加的邮件,希望对您有所帮助!

六、GitHub 源码地址

https://github.com/weiwosuoai/spring-boot-tutorial/tree/master/spring-boot-mail

赠送 | 面试&学习福利资源

最近在网上发现一个不错的 PDF 资源《Java 核心面试知识.pdf》分享给大家,不光是面试,学习,你都值得拥有!!!

获取方式: 关注公众号: 小哈学Java, 后台回复 资源,既可获取资源链接,下面是目录以及部分截图:

技术图片

技术图片

技术图片

技术图片

技术图片

技术图片

技术图片

重要的事情说两遍,获取方式: 关注公众号: 小哈学Java, 后台回复 资源,既可获取资源链接 !!!

欢迎关注微信公众号: 小哈学Java

技术图片

springboot2.0.2教程-目录

SpringBoot2.0.2教程-HelloWorld-01 SpringBoot2.0.2教程-HelloWorld之intellijidea创建web项目-02 SpringBoot2.0.2教程-配置文件application.properties-03 SpringBoot2.0.2教程-日志管理-04  SpringBoot2.0.2教 查看详情

springboot2.0集成fastdfs

SpringBoot2.0集成FastDFS前两篇整体上介绍了通过Nginx和FastDFS的整合来实现文件服务器。但是,在实际开发中对图片或文件的操作都是通过应用程序来完成的,因此,本篇将介绍SpringBoot整合FastDFS客户端来实现对图片/文件服务器的访... 查看详情

activity6.0集成springboot2.0

1、添加依赖<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM 查看详情

springboot2.0-集成redis

序最近在入门SpringBoot,然后在感慨SpringBoot较于Spring真的方便多时,顺便记录下自己在集成redis时的一些想法。1、从springboot官网查看redis的依赖包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-st 查看详情

springboot2.0实战(23)整合redis之集成缓存springdatacache

SpringBoot2.0实战(23)整合Redis之集成缓存SpringDataCache来源:https://www.toutiao.com/a6803168397090619908/?timestamp=1584450221&app=news_article_lite&group_id=6803168397090619908&req_id=20200317210341 查看详情

springboot2.0:springboot集成memcached

Memcached介绍Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对... 查看详情

怎么用html格式发送邮件.既怎么发html格式的邮件..?

...帮帮我啊???首先,我们来说一下如何发送HTML邮件。发送图文HTML邮件很简单,发送方法如下:首先,复制邮件代码,然后打开自己的邮箱,转换为代码输入方式,粘贴代码,就可以发送邮件了。详见下图(图1为QQ邮箱,图2为163邮... 查看详情

springboot2.0集成shiro出现shirodialect报错找不到abstracttextchildmodifierattrpr

 @BeanpublicShiroDialectshiroDialect(){returnnewShiroDialect();}报错出现找不到org/thymeleaf/processor/attr/AbstractTextChildModifierAttrProcessororg.springframework.beans.factory.BeanCreationException:E 查看详情

❤️git图文使用教程详解(代码片段)

✍、Git图文使用教程说明Git版本:v2.33.0IDEA版本:2021.1主要记录git的常用命令、IDEA集成git、git与GitHub、IDEA集成GitHub、Gitee等(详细图文步骤记录)配套视频参考:【尚硅谷】5h打通Git全套教程❤️Git图文使用教程详解地... 查看详情

❤️git图文使用教程详解(代码片段)

✍、Git图文使用教程说明Git版本:v2.33.0IDEA版本:2021.1主要记录git的常用命令、IDEA集成git、git与GitHub、IDEA集成GitHub、Gitee等(详细图文步骤记录)配套视频参考:【尚硅谷】5h打通Git全套教程❤️Git图文使用教程详解地... 查看详情

❤️git图文使用教程详解(代码片段)

✍、Git图文使用教程说明Git版本:v2.33.0IDEA版本:2021.1主要记录git的常用命令、IDEA集成git、git与GitHub、IDEA集成GitHub、Gitee等(详细图文步骤记录)配套视频参考:【尚硅谷】5h打通Git全套教程❤️Git图文使用教程详解地... 查看详情

Paypal php MySQL 集成教程

】PaypalphpMySQL集成教程【英文标题】:PaypalphpMySQLintegrationtutorial【发布时间】:2011-06-2121:30:01【问题描述】:我的网页上有一个完整的自动通知系统,它是一个简单的PHP脚本,它在数据库中搜索电子邮件,然后向每个人发送一封... 查看详情

2018最新springboot2.0教程(零基础入门)

一、零基础快速入门SpringBoot2.01、SpringBoot2.x课程全套介绍和高手系列知识点简介:介绍SpringBoot2.x课程大纲章节java基础,jdk环境,maven基础2、SpringBoot2.x依赖环境和版本新特性说明简介:讲解新版本依赖环境和springboot2新特性概述3... 查看详情

odoo邮件发送集成

参考技术AODOO邮件发送集成电子邮件这个场景在国外集成率非常高,国内则相对少很多。一是因为文化习惯,而且我们还有微信、钉钉;二是因为Mail模块是针对国际化普世标准设计的,如Gmail、Postfix,不太适合中国大部分中小企... 查看详情

springboot2.0集成elk7.6.2(代码片段)

小伙伴们,你们好,我是老寇注:请点击我,获取源码mysql安装包链接:https://pan.baidu.com/s/1swrV9ffJnmz4S0mfkuBbIw 提取码:1111目录一、前提条件二、集成过程一、前提条件1.es7.6.2集群2.安装kibana7.6.2logstash7.6.2二... 查看详情

git实操图文详解系列教程——idea集成github

版权声明本文原创作者:谷哥的小弟作者博客地址:http://blog.csdn.net/lfdfhl开发环境本系列教程所涉开发环境,详情如下:1、Win102、JDK1.83、Git2.31.14、IDEA2021.2.1参考资料本系列教程在撰写过程中所涉及参考资料,... 查看详情

git实操图文详解系列教程——idea集成gitee

版权声明本文原创作者:谷哥的小弟作者博客地址:http://blog.csdn.net/lfdfhl开发环境本系列教程所涉开发环境,详情如下:1、Win102、JDK1.83、Git2.31.14、IDEA2021.2.1参考资料本系列教程在撰写过程中所涉及参考资料,... 查看详情

git实操图文详解系列教程——idea集成gitee

版权声明本文原创作者:谷哥的小弟作者博客地址:http://blog.csdn.net/lfdfhl开发环境本系列教程所涉开发环境,详情如下:1、Win102、JDK1.83、Git2.31.14、IDEA2021.2.1参考资料本系列教程在撰写过程中所涉及参考资料,... 查看详情