展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > SpringBoot实现定时发送邮件的方法有哪些

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

一、发送邮件的三种方法1、发送纯文本邮件2、发送复杂邮件3、发送模板邮件二、定时任务介绍Spring框架的定时任务调度功能支持配置和注解两种方式SpringBoot在Spring框架的基础上实现了继承,并对其中基于注解方式的定时任务实现了非常好的支持。下面,针对SpringBoot项目中基于注解方式的定时任务调度的相关注解和使用进行介绍。1.@EnableScheduling@EnableScheduling注解是Spring框架提供的,用于开启基于注解方式的定时任务支持,该注解主要用在项目启动类上。2.

本文目录

    一、发送邮件的三种方法

    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实现定时发送邮件的方法有哪些

    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邮箱认为是垃圾邮件,就会出现报错,所以尽量不要进行邮箱轰炸。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。

    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。