Skip to content

common-mail-starter

1. 功能介绍

1.便捷依赖引入

  • 提供标准化的邮件发送依赖,快速集成邮件发送功能。

2.灵活的配置支持

  • 支持主流邮箱服务商的 SMTP 协议,兼容性强。

3.完善的加密与安全机制

  • 支持 SSL/TLS 加密,保障邮件传输的安全性。
  • 配置中包含身份验证、字符集编码等通用设置,避免开发者重复配置。

2. 配置示例

yml
spring:
  mail:
    host: ${MAIL_HOST} # 邮箱服务商的SMTP服务器地址
    username: ${MAIL_USERNAME} # 邮箱账户
    password: ${MAIL_PASSWORD} # 邮箱授权码或密码

3.案例演示

1.创建模块

CleanShot 2025-01-20 at 14.03.38@2x

2.目录结构

CleanShot 2025-01-20 at 14.11.41@2x

3.pom.xml

1.基本配置
xml
<!-- 通过properties来指定版本号 -->
<properties>
    <!-- 指定编译版本 -->
    <java.version>1.8</java.version>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- 指定Sunrays-Framework的版本 -->
    <sunrays.version>1.0.0</sunrays.version>
</properties>

<dependencyManagement>
<!-- 使用sunrays-dependencies来管理依赖,则依赖无需加版本号 -->
<dependencies>
    <dependency>
        <groupId>cn.sunxiansheng</groupId>
        <artifactId>sunrays-dependencies</artifactId>
        <version>${sunrays.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>
</dependencyManagement>
2.引入依赖
xml
<dependencies>
    <!-- common-mail-starter -->
    <dependency>
        <groupId>cn.sunxiansheng</groupId>
        <artifactId>common-mail-starter</artifactId>
    </dependency>
    <!-- 必须引入 -->
    <dependency>
        <groupId>cn.sunxiansheng</groupId>
        <artifactId>common-log4j2-starter</artifactId>
    </dependency>

    <!-- 测试用的Web模块 -->
    <dependency>
        <groupId>cn.sunxiansheng</groupId>
        <artifactId>common-web-starter</artifactId>
    </dependency>
    <!-- env模块确保数据安全 -->
    <dependency>
        <groupId>cn.sunxiansheng</groupId>
        <artifactId>common-env-starter</artifactId>
    </dependency>
</dependencies>

4.application.yml 配置日志根目录、.env文件的绝对路径以及mail

yaml
sun-rays:
  log4j2:
    home: /Users/sunxiansheng/IdeaProjects/sunrays-framework-demo/common-mail-starter-demo/logs # 日志根目录(默认./logs)
  env:
    path: /Users/sunxiansheng/IdeaProjects/sunrays-framework-demo/common-mail-starter-demo # .env文件的绝对路径
spring:
  mail:
    host: ${MAIL_HOST} # 邮箱服务商的SMTP服务器地址
    username: ${MAIL_USERNAME} # 邮箱账户
    password: ${MAIL_PASSWORD} # 邮箱授权码或密码

5..env 填写mail的配置信息

properties
MAIL_HOST= 邮箱服务商的SMTP服务器地址
MAIL_USERNAME= 邮箱账户
MAIL_PASSWORD= 邮箱授权码或密码

6.MailController.java 发送四种类型的邮件

java
package cn.sunxiansheng.mail.controller;

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 javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: 邮件服务
 *
 * @Author sun
 * @Create 2025/1/2 17:52
 * @Version 1.0
 */
@RestController
public class MailController {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String to = "你想要发送的人的邮箱";

    /**
     * 发送简单邮件
     */
    @RequestMapping("/sendSimpleMail")
    public void sendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject("使用JavaMailSender和SimpleMailMessage发送邮件");
        message.setText("这是我用Springboot自带的mail启动器给你发送的邮件,当前时间是: " + simpleDateFormat.format(new Date()));
        mailSender.send(message);
    }

    /**
     * 发送HTML邮件
     */
    @RequestMapping("/sendHtmlMessage")
    public void sendHtmlMessage() {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 创建邮件发送者地址
            helper.setFrom(new InternetAddress(MimeUtility.encodeText("发送者") + "<" + from + ">"));
            // 创建邮件发送者地址
            helper.setTo(new InternetAddress(MimeUtility.encodeText("接收方") + "<" + to + ">"));
            // 标题
            helper.setSubject("这是一份内容包含HTML标签的网页");
            String content = "<h1>中奖通知</h1>" +
                    "<p style='color:red;'>恭喜你获得大乐透三等奖,点击此处<a>https://www.baidu.com<a>进行领奖</p>";
            // 第二个参数指定发送的是HTML格式
            helper.setText(content, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     */
    @RequestMapping("/sendAttachmentsMail")
    public void sendAttachmentsMail() {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 创建邮件发送者地址
            helper.setFrom(new InternetAddress(MimeUtility.encodeText("发送者") + "<" + from + ">"));
            // 创建邮件发送者地址
            helper.setTo(new InternetAddress(MimeUtility.encodeText("接收方") + "<" + to + ">"));
            helper.setSubject("报销申请-报销明细在附件里");
            String content = "<h1>报销单</h1>" +
                    "<p style='color:red;'>报销详情请下载附件进行查看</p>";
            // 第二个参数指定发送的是HTML格式
            helper.setText(content, true);
            // 添加附件
            helper.addAttachment("报销费用.png", new FileSystemResource(new File("/Users/sunxiansheng/Pictures/image.png")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    /**
     * 发送带静态资源的邮件
     */
    @RequestMapping("/sendInlineMail")
    public void sendInlineMail() {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 创建邮件发送者地址
            helper.setFrom(new InternetAddress(MimeUtility.encodeText("发送者") + "<" + from + ">"));
            // 创建邮件发送者地址
            helper.setTo(new InternetAddress(MimeUtility.encodeText("接收方") + "<" + to + ">"));
            helper.setSubject("邮件里包含静态资源,请注意查收");
            //第二个参数指定发送的是HTML格式
            helper.setText("<html><body>带静态资源的邮件内容 图片:<img src='cid:fee'/></body></html>", true);

            FileSystemResource file = new FileSystemResource(new File("/Users/sunxiansheng/Pictures/image.png"));
            helper.addInline("fee", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }
}

7.MailApplication.java 启动类

java
package cn.sunxiansheng.mail;

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

/**
 * Description: MailApplication
 *
 * @Author sun
 * @Create 2025/1/20 14:05
 * @Version 1.0
 */
@SpringBootApplication
public class MailApplication {

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

8.测试

1.发送简单邮件

CleanShot 2025-01-20 at 14.15.35@2x

CleanShot 2025-01-20 at 14.16.33@2x

2.发送HTML邮件

CleanShot 2025-01-20 at 14.17.37@2x

CleanShot 2025-01-20 at 14.18.08@2x

3.发送带附件的邮件

CleanShot 2025-01-20 at 14.17.43@2x

CleanShot 2025-01-20 at 14.18.29@2x

4.发送带静态资源的邮件

CleanShot 2025-01-20 at 14.17.49@2x

CleanShot 2025-01-20 at 14.18.49@2x