SpringBoot Java邮件发送工具类

1、引入依赖 pom.xml

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、增加配置 application.yml

xml 复制代码
spring:
	mail:
        # 发送邮件的服务器,笔者这里使用的 QQ 邮件
        host: smtp.qq.com
        username: ***@qq.com
        password: ***
        properties.mail.smtp.auth: true
        properties.mail.smtp.starttls.enable: true
        default-encoding: utf-8

3、发送邮件工具类 SendMailUtils.java

java 复制代码
package com.company.mail.utils;

import com.company.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

/**
 * 发送邮件工具类
 *
 * @author ZhangJi
 */
@Slf4j
public class SendMailUtils {

    private SendMailUtils() {}

    private static final MailProperties MAIL_PROPERTIES;
    private static final JavaMailSender MAIL_SENDER;

    static {
        MAIL_PROPERTIES = SpringUtils.getBean(MailProperties.class);
        MAIL_SENDER = SpringUtils.getBean(JavaMailSender.class);
    }

    /**
     * 发送简单文本的邮件
     * @param target 目标邮箱
     * @param subject 标题
     * @param content 内容
     * @return 发送结果
     */
    public static boolean sendSimpleMail(String target, String subject, String content) {

        return sendHtmlMail(target, subject, content);
    }

    /**
     * 发送 html 的邮件
     * @param target 目标邮箱
     * @param subject 标题
     * @param html 内容
     * @return 发送结果
     */
    public static boolean sendHtmlMail(String target, String subject, String html) {

        return sendAffixMail(target, subject, html, null);
    }

    /**
     * 发送发票邮件
     * @param target 目标邮箱
     * @param subject 标题
     * @param filePath 发票附件
     * @return 发送结果
     */
    public static boolean sendInvoiceMail(String target, String subject, String filePath) {

        return sendAffixMail(target, subject, "<p>尊敬的用户您好:</p><p>您的发票已开出,请查收。</p>", new String[] {filePath});
    }

    /**
     * 发送带有附件的邮件
     * @param target 目标邮箱
     * @param subject 标题
     * @param content 内容
     * @param filePaths 附件列表
     * @return 结果
     */
    public static boolean sendAffixMail(String target, String subject, String content, String[] filePaths) {
        log.info("## Ready to send mail ...");
        MimeMessage mimeMessage = MAIL_SENDER.createMimeMessage();

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

            // 添加附件
            if(null != filePaths && filePaths.length > 0) {
                for (int i = 0; i < filePaths.length; i++) {
                    FileSystemResource file = new FileSystemResource(filePaths[i]);
                    String fileName = "附件" + (i + 1) + "_" + file.getFile().getName();
                    mimeMessageHelper.addAttachment(fileName, file);
                }
            }

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

    public static MailProperties getMailProperties() {
        return MAIL_PROPERTIES;
    }

    public static JavaMailSender getMailSender() {
        return MAIL_SENDER;
    }
}

4、测试类 MailTest.java

java 复制代码
package com.company.test;

import com.company.PlatformApplication;
import com.company.common.config.PlatformConfig;
import com.company.common.constant.Constants;
import com.company.mail.utils.SendMailUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PlatformApplication.class)
public class MailTest {

    @Test
    public void sendInvoiceMail() {
        String filePath = "/profile/upload/2026/04/10/20260410092201A001.png";
        filePath = filePath.contains("http")?filePath: filePath.replace(Constants.RESOURCE_PREFIX, PlatformConfig.getProfile());
        System.out.println(SendMailUtils.sendInvoiceMail("1661623520@qq.com", "发票开具通知", filePath));
    }
}

使用说明

对应的工具类,如:字符串等,换成自己的即可。

个人博客:紫琪软件工作室

邮箱留言:zhangji_59@qq.com

相关推荐
右耳朵猫AI几秒前
Java/JVM周刊2026W21 | Java 26发布、JDK 27抢先体验、Spring Boot 4.1预告、GlassFish 8.0.2发布
java·jvm·spring boot
Knight_AL2 分钟前
MyBatis 报错:Parameter ‘xxx‘ not found 的原因与解决方案
java·tomcat·mybatis
一条泥憨鱼5 分钟前
Java网络编程:Socket通信从入门到起飞
java·开发语言·网络·网络编程
西安邮电大学10 分钟前
分布式锁三种实现
java·redis·后端·其他·面试
码不停蹄的玄黓13 分钟前
SpringBoot 实现自定义注解
java·spring boot·spring
施棠海19 分钟前
自定义并可深度定制的数字滚动选择器完整源代码与相关注意事项
java·开发语言
2601_9611940231 分钟前
2026六级词汇资料电子版|大学英语六级核心词汇PDF
java·spring·eclipse·pdf·tomcat·hibernate
布朗克16833 分钟前
18 面向对象综合实战——设计一个图书管理系统
java·面试·职场和发展·面向对象实战
码不停蹄的玄黓43 分钟前
旁路缓存(Cache-Aside,CA)
java·开发语言
NGINX开源社区43 分钟前
NGINX Ingress Controller 中的 Cache Policy:VirtualServer 实战指南
java·前端·nginx