Table of Contents
一、发送邮件的三种方法
二、定时任务介绍
1.@EnableScheduling
2.@Scheduled
三、前期准备工作
1、登录QQ邮箱获取授权码
第一步:进入QQ邮箱
第二步:找到POP3/SMTP,并开启
第三步:复制授权码
2、pom.xml中的依赖
3、在全局配置文件application.properties添加邮件服务配置
四、操作
一、创建邮件发送任务管理的业务处理类SendEmailService
二、在test类中发送邮件
二月二龙抬头!
三、发送定时邮件
四、在项目启动类上添加基于注解的定时任务支持:@EnableScheduling
Home Java javaTutorial What are the methods for sending emails regularly in SpringBoot?

What are the methods for sending emails regularly in SpringBoot?

May 16, 2023 pm 05:52 PM
springboot

一、发送邮件的三种方法

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邮箱

What are the methods for sending emails regularly in SpringBoot?

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

What are the methods for sending emails regularly in SpringBoot?

第三步:复制授权码

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

What are the methods for sending emails regularly in SpringBoot?

2、pom.xml中的依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--添加下面的依赖后,Spring Boot自动配置的邮件服务会生效,在邮件发送任务时,
            可以直接使用Spring框架提供的JavaMailSender接口或者它的实现类JavaMailSenderImpl邮件        
        发送-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>
Copy after login

What are the methods for sending emails regularly in 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
Copy after login

四、操作

一、创建邮件发送任务管理的业务处理类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();
        }
    }
 
}
Copy after login

二、在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("<html><head></head>");
        text.append("<body><h2 id="二月二龙抬头">二月二龙抬头!</h2>");
        // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。
        String rscId = "img001";
        text.append("<img  src=&#39;cid:" +rscId+"&#39;/ alt="What are the methods for sending emails regularly in SpringBoot?" ></body>");
        text.append("</html>");
        // 指定静态资源文件和附件路径
        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);
    }
}
Copy after login

模板文件的html(emailTemplate_vercode.html)

<!DOCTYPE html>
<html lang="en">
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>用户验证码</title>
</head>
<body>
<div><span th:text="${username}">XXX</span> 先生/女士,您好:</div>
<P >您的新用户验证码为<span th:text="$[code]" >123456</span>,请妥善保管。</P>
</body>
</html>
Copy after login

三、发送定时邮件

下面类中的 @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("<html><head></head>");
        text.append("<body><h2 id="二月二龙抬头">二月二龙抬头!</h2>");
        // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。
        String rscId = "img001";
        text.append("<img  src=&#39;cid:" +rscId+"&#39;/ alt="What are the methods for sending emails regularly in SpringBoot?" ></body>");
        text.append("</html>");
        // 指定静态资源文件和附件路径
        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);
    }
}
Copy after login

四、在项目启动类上添加基于注解的定时任务支持:@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);
    }
 
}
Copy after login

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

The above is the detailed content of What are the methods for sending emails regularly in SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles