springboot集成mail快速入门demo

一、简介

在日常工作开发中,发送邮件功能有时需要我们去开发使用,这里首先介绍以下与发送接受邮件相关的一些协议:

  • 发送邮件:SMPT、MIME,是一种基于"推"的协议,通过SMPT协议将邮件发送至邮件服务器,MIME协议是对SMPT协议的一种补充,如发送图片附件等
  • 接收邮件:POP、IMAP,是一种基于"拉"的协议,收件人通过POP协议从邮件服务器拉取邮件

二、账号准备

Gmail 客户端设置说明:参考官方Gmail帮助

三、代码工程

pom.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mail</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

</project>

application.properties

ini 复制代码
#这里以qq邮箱为例
# qq邮箱服务器
spring.mail.host=smtp.qq.com
# 你的qq邮箱账户
spring.mail.username=yourAccount@qq.com
# 你的qq邮箱第三方授权码
spring.mail.password=yourPassword
# 编码类型
spring.mail.default-encoding=UTF-8
spring.thymeleaf.prefix=classpath:/template/

DemoApplication.java

typescript 复制代码
package com.et.mail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

MailUtil.java

typescript 复制代码
package com.et.mail.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author zhaokuii11@163.com
 * @create 2022-01-11 19:22
 * @Description
 */
@Service
public class MailUtils {
    // 日志
    private final Logger logger = LoggerFactory.getLogger(MailUtils.class);
    @Value("${spring.mail.username}") //注入 application.properties中指定的用户名
    private String from;

    @Autowired //用于发送文件
    private JavaMailSender mailSender;


    /**
     * 发送普通文本邮件
     *
     * @param to      收件人
     * @param subject 主体
     * @param content 内容
     */
    public void sendSimpleMail(
            String to, String subject, String content
    ) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(from);//发信人

        mailSender.send(message);
    }

    /**
     * 发送html邮件
     *
     * @param to      收件人
     * @param subject 书体
     * @param content 内容(可以包含html等标签)
     */
    public void sendHtmlMail(
            String to, String subject, String content
    ) {
        //使用MimeMessage,MIME协议
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支持html
            mailSender.send(message);
            logger.info("发送HTML邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("发送HTML邮件失败:", e);
        }

    }


    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主体
     * @param content  内容
     * @param filePath 附件路径
     */
    public void sendAttachmentMail(
            String to, String subject,
            String content, String filePath
    ) {
        // 日志
        logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, filePath);
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件,如附件,图片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
            mailSender.send(message);
            logger.info("发送带附件邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带附件邮件失败", e);
        }

    }

    /**
     * 发送带图片的邮件
     *
     * @param to      收件人
     * @param subject 主体
     * @param content 内容
     * @param rscPath 图片路径
     * @param rscId   rscId 图片ID,用于在<img\>标签中使用,从而显示图片
     */
    public void sendInlineResourceMail(
            String to, String subject, String content,
            String rscPath, String rscId) {
        // 日志
        logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);//重复使用添加多个图片
            mailSender.send(message);
            logger.info("发送带图片邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带图片邮件失败", e);
        }
    }
}

邮件模板

xml 复制代码
<!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.bestbpf.com/register/{id}(id=${id})}">激活账户</a>
</body>
</html>

代码仓库

四、测试

typescript 复制代码
package com.et;

import com.et.mail.DemoApplication;
import com.et.mail.util.MailUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * @author zhaokuii11@163.com
 * @create 2022-01-11 19:49
 * @Description
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class SpringBootApplicationTest {
    @Autowired
    MailUtils mailUtils;
    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 指定模板发送邮件
     */
    /**
     * 指定模板发送邮件
     */
    @Test
    public void testTemplateMail() {
        //向Thymeleaf模板传值,并解析成字符串
        Context context = new Context();
        context.setVariable("id", "001");
        String emailContent = templateEngine.process("emailTemplate", context);
        mailUtils.sendHtmlMail("zhaokuii11@163.com", "这是一个模板文件", emailContent);
    }
    /**
     * 发送简单纯文本邮件
     */
    @Test
    public void sendSimpleMail() {
        mailUtils.sendSimpleMail("zhaokuii11@163.com", "发送邮件测试", "大家好,这是我用springboot进行发送邮件测试");
    }

    /**
     * 发送HTML邮件
     */
    @Test
    public void sendHtmlMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件" + "</font></h3></body></html>";
        mailUtils.sendHtmlMail("zhaokuii11@163.com", "发送邮件测试", content);
    }

    /**
     * 发送带附件的邮件
     */
    @Test
    public void sendAttachmentMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件,有附件哦" + "</font></h3></body></html>";
        String filePath = "your file path";
        mailUtils.sendAttachmentMail("zhaokuii11@163.com", "发送邮件测试", content, filePath);
    }

    /**
     * 发送带图片的邮件
     */
    @Test
    public void sendInlineResourceMail() {
        String rscPath = "your picture path";
        String rscId = "001";
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件,有图片哦" + "</font></h3>"
                + "<img src=\'cid:" + rscId + "\'></body></html>";
        mailUtils.sendInlineResourceMail("zhaokuii11@163.com", "发送邮件测试", content, rscPath, rscId);
    }
}

五、引用

相关推荐
皮皮林55112 分钟前
SpringBoot 集成 Hera,让日志查看从 “找罪证” 变 “查答案”!
spring boot
num_killer17 分钟前
小白的Langchain学习
java·python·学习·langchain
期待のcode1 小时前
Java虚拟机的运行模式
java·开发语言·jvm
程序员老徐1 小时前
Tomcat源码分析三(Tomcat请求源码分析)
java·tomcat
a程序小傲1 小时前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先
仙俊红1 小时前
spring的IoC(控制反转)面试题
java·后端·spring
阿湯哥1 小时前
AgentScope Java 集成 Spring AI Alibaba Workflow 完整指南
java·人工智能·spring
小楼v1 小时前
说说常见的限流算法及如何使用Redisson实现多机限流
java·后端·redisson·限流算法
与遨游于天地2 小时前
NIO的三个组件解决三个问题
java·后端·nio
czlczl200209252 小时前
Guava Cache 原理与实战
java·后端·spring