0

0

SpringBoot实现定时发送邮件的方法有哪些

PHPz

PHPz

发布时间:2023-05-16 17:52:49

|

1462人浏览过

|

来源于亿速云

转载

一、发送邮件的三种方法

1、发送纯文本邮件2、发送复杂邮件3、发送模板邮件

二、定时任务介绍

spring框架的定时任务调度功能支持配置和注解两种方式spring boot在spring框架的基础上实现了继承,并对其中基于注解方式的定时任务实现了非常好的支持。下面,我们将介绍基于注解方式实现定时任务调度的相关注解和使用,适用于 spring boot 项目。

1.@EnableScheduling

@EnableScheduling 注解是 Spring 框架提供的,用于开启基于注解方式的定时任务支持,该注解主要用在项目启动类上。

2.@Scheduled

@Scheduled 注解同样是 Spring 框架提供的,配置定时任务的执行规则,该注解主要用在定时业务方法上。使用 @Scheduled 注解可以灵活配置定时任务的执行规则,其属性多样,能够实现精细化的调度

属性 说明
cron 类似于 cron 的表达式,可以定制定时任务触发的秒、分钟、小时、月中的日、月、周中的日
zone 表示在上一次任务执行结束后在指定时间后继续执行下一次任务(属性值为long类型)
fixedDelay 指定cron 表达式将被解析的时区。默认情况下,该属性是空字符串(即使用服务器的本地时区
fixedDelayString 表示在上一次任务执行结束后在指定时间后继续执行下一次任务(属性值为long类型的字符串形式)
fixedRate 表示每隔指定时间执行一次任务 (属性值为 long 类型)
fixedRateString 表示每隔指定时间执行一次任务(属性值为 long 类型的字符串形式)
initialDelay 表示在fixedRate 或fixedDelay 任务第一次执行之前要延迟的毫秒数(属性值为long类型)
initialDelayString 表示在fixedRate或fixedDelay 任务第一次执行之前要延迟的毫秒数(属性值为long类型的字符串形式)

三、前期准备工作

1、登录QQ邮箱获取授权码

第一步:进入QQ邮箱

SpringBoot实现定时发送邮件的方法有哪些

第二步:找到POP3/SMTP,并开启

SpringBoot实现定时发送邮件的方法有哪些

第三步:复制授权码

开启过程需要手机号码验证,按照步骤操作即可。开启成功之后,即可获取一个授权码,将该号码保存好,一会使用

SpringBoot实现定时发送邮件的方法有哪些

极限网络办公Office Automation
极限网络办公Office Automation

专为中小型企业定制的网络办公软件,富有竞争力的十大特性: 1、独创 web服务器、数据库和应用程序全部自动傻瓜安装,建立企业信息中枢 只需3分钟。 2、客户机无需安装专用软件,使用浏览器即可实现全球办公。 3、集成Internet邮件管理组件,提供web方式的远程邮件服务。 4、集成语音会议组件,节省长途话费开支。 5、集成手机短信组件,重要信息可直接发送到员工手机。 6、集成网络硬

下载

2、pom.xml中的依赖


        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
 
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-mail
        
    

SpringBoot实现定时发送邮件的方法有哪些

3、在全局配置文件application.properties添加邮件服务配置

# 发件人邮件服务器相关配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
# 配置个人QQ账户和密码(这里需要大家修改为自己的QQ账号和密码,密码是加密后的授权码,授权码的获得后继讲解)
spring.mail.username=QQ@qq.com
spring.mail.password=填入刚刚复制的授权码
spring.mail.default-encoding=UTF-8
# 邮件服务超时时间配置
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

四、操作

一、创建邮件发送任务管理的业务处理类SendEmailService

注意:在方法上的注解@Async是需要搭配定时任务一起使用的,如果使用普通的test类时可以不用这个注解的

package com.lyn.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
 
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
 
/**
 * @author:Lyn.R
 * @date:2023-02-21 14:54:36
 * @Description:
 * @note:
 **/
@Service
public class SendEmailService {
    @Autowired
    private JavaMailSenderImpl mailSender;//使用Spring框架提供的实现类JavaMailSenderImpl来实现邮件发送。
    @Value("${spring.mail.username}")//借助@Value注解读取全局变量中的spring.mail.username的值来作发件人
    private String from;
    /**
     * 第一种方法:发送纯文本邮件
     * @param to      收件人地址
     * @param subject 邮件标题
     * @param text    邮件内容
     */
   @Async
    public void sendSimpleEmail(String to, String subject, String text) {
        // 定制纯文本邮件信息SimpleMailMessage
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);//设置发件人
        message.setTo(to);//设置收件人
        message.setSubject(subject);//设置邮件标题
        message.setText(text);//设置 正文件内容
        try {
            // 发送邮件
            mailSender.send(message);
            System.out.println("纯文本邮件发送成功");
        } catch (MailException e) {
            System.out.println("纯文本邮件发送失败 " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 第二种方法:发送复杂邮件(包括静态资源和附件)
     * @param to           收件人地址
     * @param subject      邮件标题
     * @param text         邮件内容
     * @param filePath     附件地址
     * @param rscId        静态资源唯一标识
     * @param rscPath      静态资源地址
     */
    //sendComplexEmail()方法需要接收的参数除了基本的发送信息外,还包括静态资源唯一标识、静态资源路径和附件路径
    @Async
    public void sendComplexEmail(String to,String subject,String text,String filePath,String rscId,String rscPath){
        // 定制复杂邮件信息MimeMessage
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // 使用MimeMessageHelper帮助类对邮件信息封装处理 ,并设置multipart多部件使用为true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            // 设置邮件静态资源
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);//设置邮件静态资源的方法
            // 设置邮件附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);//设置邮件附件的方法
            // 发送邮件
            mailSender.send(message);
            System.out.println("复杂邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("复杂邮件发送失败 "+e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 第三钟方法:发送模板邮件
     * @param to       收件人地址
     * @param subject  邮件标题
     * @param content  邮件内容
     */
    @Async
    public void sendTemplateEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // 使用MimeMessageHelper帮助类对邮件信息进行封装处理,并设置multipart多部件使用为true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            // 发送邮件
            mailSender.send(message);
            System.out.println("模板邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("模板邮件发送失败 "+e.getMessage());
            e.printStackTrace();
        }
    }
 
}

二、在test类中发送邮件

package com.lyn;
 
import com.lyn.service.SendEmailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
 
@SpringBootTest
class SpringbootHomeworkEmail0221ApplicationTests {
 
    @Autowired
    private SendEmailService sendEmailService;
    @Test
    public void sendSimpleMailTest() {
        String to="12345678@qq.com";//这里修改为你能接收到的邮箱
        String subject="【纯文本邮件】标题";
        String text="嘟嘟嘟.....";
        // 发送简单邮件
        sendEmailService.sendSimpleEmail(to,subject,text);
    }
    @Test
    public void sendComplexEmailTest() {
        //根据前面定义的复杂邮件发送业务定制各种参数
        String to="12345678@qq.com";//修改为你自己的邮件方便接收查看
        String subject="【复杂邮件】标题";
        // 定义邮件内容
        StringBuilder text = new StringBuilder();
        //对邮件内容使用了HTML标签编辑邮件内容
        text.append("");
        text.append("

二月二龙抬头!

"); // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。 String rscId = "img001"; text.append("@@##@@"); text.append(""); // 指定静态资源文件和附件路径 String rscPath="D:\\1.jpg";//注意这里修改为你的硬盘中有的资源 String filePath="D:\\hahaha.txt";//注意这里修改为你的硬盘中有的资源 // 发送复杂邮件 sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath); } @Autowired private TemplateEngine templateEngine; @Test public void sendTemplateEmailTest() { String to="12345678@qq.com"; String subject="【模板邮件】标题"; // 使用模板邮件定制邮件正文内容 Context context = new Context();//Context注意正确导入“import org.thymeleaf.context.Context;” context.setVariable("username", "石头"); context.setVariable("code", "456123"); // 使用TemplateEngine设置要处理的模板页面 String emailContent = templateEngine.process("emailTemplate_vercode", context); // 发送模板邮件 sendEmailService.sendTemplateEmail(to,subject,emailContent); } }

模板文件的html(emailTemplate_vercode.html)





    
    用户验证码


XXX 先生/女士,您好:

您的新用户验证码为123456,请妥善保管。

三、发送定时邮件

下面类中的 @Scheduled(cron = "*/5 * * * * ?")表达式大家可以去下面的网址生成Cron - 在线Cron表达式生成器 (ciding.cc)

package com.lyn.controller;
 
import com.lyn.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
 
/**
 * @author:Lyn.R
 * @date:2023-02-21 19:55:01
 * @Description:
 * @note:
 **/
@Controller
public class MyScheduled {
    @Autowired
    private SendEmailService sendEmailService;
 
    @Autowired
    //模板引擎(Template Engine), 是用来解析对应类型模板文件然后动态生成由数据和静态页面组成的视图文件的一个工具
    private TemplateEngine templateEngine;
 
    @Scheduled(cron = "*/5 * * * * ?")
    public void sendSimpleMailTest() {
        String to="12345678@qq.com";//这里修改为你能接收到的邮箱
        String subject="【纯文本邮件】标题";
        String text="嘟嘟嘟.....";
        // 发送简单邮件
        sendEmailService.sendSimpleEmail(to,subject,text);
    }
    @Scheduled(cron = "1 * * * * ?  ")
    public void sendComplexEmailTest() {
        //根据前面定义的复杂邮件发送业务定制各种参数
        String to="12345678@qq.com";//修改为你自己的邮件方便接收查看
        String subject="【复杂邮件】标题";
        // 定义邮件内容
        StringBuilder text = new StringBuilder();
        //对邮件内容使用了HTML标签编辑邮件内容
        text.append("");
        text.append("

二月二龙抬头!

"); // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。 String rscId = "img001"; text.append("@@##@@"); text.append(""); // 指定静态资源文件和附件路径 String rscPath="D:\\1.jpg";//注意这里修改为你的硬盘中有的资源 String filePath="D:\\hahaha.txt";//注意这里修改为你的硬盘中有的资源 // 发送复杂邮件 sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath); } @Scheduled(cron = "0 * * * * ? ") public void sendTemplateEmailTest() { String to="12345678@qq.com"; String subject="【模板邮件】标题"; // 使用模板邮件定制邮件正文内容 Context context = new Context();//Context注意正确导入“import org.thymeleaf.context.Context;” context.setVariable("username", "石头"); context.setVariable("code", "456123"); // 使用TemplateEngine设置要处理的模板页面 String emailContent = templateEngine.process("emailTemplate_vercode", context); // 发送模板邮件 sendEmailService.sendTemplateEmail(to,subject,emailContent); } }

四、在项目启动类上添加基于注解的定时任务支持:@EnableScheduling

package com.lyn;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
 
@SpringBootApplication
@EnableScheduling
public class SpringbootHomeworkEmail0221Application {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootHomeworkEmail0221Application.class, args);
    }
 
}

注意:邮件发多了,可能会导致qq邮箱认为是垃圾邮件,就会出现报错,所以尽量不要进行邮箱轰炸。

SpringBoot实现定时发送邮件的方法有哪些SpringBoot实现定时发送邮件的方法有哪些

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
php中文乱码如何解决
php中文乱码如何解决

本文整理了php中文乱码如何解决及解决方法,阅读节专题下面的文章了解更多详细内容。

1

2026.01.28

Java 消息队列与异步架构实战
Java 消息队列与异步架构实战

本专题系统讲解 Java 在消息队列与异步系统架构中的核心应用,涵盖消息队列基本原理、Kafka 与 RabbitMQ 的使用场景对比、生产者与消费者模型、消息可靠性与顺序性保障、重复消费与幂等处理,以及在高并发系统中的异步解耦设计。通过实战案例,帮助学习者掌握 使用 Java 构建高吞吐、高可靠异步消息系统的完整思路。

1

2026.01.28

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

23

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

120

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

50

2026.01.26

苹果官方查询网站 苹果手机正品激活查询入口
苹果官方查询网站 苹果手机正品激活查询入口

苹果官方查询网站主要通过 checkcoverage.apple.com/cn/zh/ 进行,可用于查询序列号(SN)对应的保修状态、激活日期及技术支持服务。此外,查找丢失设备请使用 iCloud.com/find,购买信息与物流可访问 Apple (中国大陆) 订单状态页面。

191

2026.01.26

npd人格什么意思 npd人格有什么特征
npd人格什么意思 npd人格有什么特征

NPD(Narcissistic Personality Disorder)即自恋型人格障碍,是一种心理健康问题,特点是极度夸大自我重要性、需要过度赞美与关注,同时极度缺乏共情能力,背后常掩藏着低自尊和不安全感,影响人际关系、工作和生活,通常在青少年时期开始显现,需由专业人士诊断。

7

2026.01.26

windows安全中心怎么关闭 windows安全中心怎么执行操作
windows安全中心怎么关闭 windows安全中心怎么执行操作

关闭Windows安全中心(Windows Defender)可通过系统设置暂时关闭,或使用组策略/注册表永久关闭。最简单的方法是:进入设置 > 隐私和安全性 > Windows安全中心 > 病毒和威胁防护 > 管理设置,将实时保护等选项关闭。

7

2026.01.26

2026年春运抢票攻略大全 春运抢票攻略教你三招手【技巧】
2026年春运抢票攻略大全 春运抢票攻略教你三招手【技巧】

铁路12306提供起售时间查询、起售提醒、购票预填、候补购票及误购限时免费退票五项服务,并强调官方渠道唯一性与信息安全。

183

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Redis6入门到精通超详细教程
Redis6入门到精通超详细教程

共47课时 | 5.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号