springboot实现定时发邮箱

本文介绍了如何在SpringBoot项目中使用@Scheduled注解配置定时任务,并详细讲解了@Scheduled的各个属性。此外,还展示了如何集成邮件发送功能,包括添加依赖、配置邮件服务以及创建发送邮件的业务处理类SendEmailService,支持发送纯文本、复杂(含静态资源和附件)和模板邮件。
摘要由CSDN通过智能技术生成

前言

小编我将用CSDN记录软件开发求学之路上亲身所得与所学的心得与知识,有兴趣的小伙伴可以关注一下!

也许一个人独行,可以走的很快,但是一群人结伴而行,才能走的更远!让我们在成长的道路上互相学习,让我们共同进步,欢迎关注!

一、定时任务介绍

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:在pom.xml文件中添加实现纯文本邮件依赖启动器

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2:在全局配置文件application.properties添加邮件服务股配置

#发件人邮箱服务器相关配置
spring.mail.host=smtp.qq.com
spring.mail.port=587#这里是QQ邮箱的端口号,但其他邮箱要写对应的主机,端口号
#配置个人QQ账号和密码(这里需要大家修改为自己的发件人的)
spring.mail.username=1234566@qq.com
spring.mail.password=abcdefghijklmn
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

三、在service包中创建邮件发送任务的业务处理类SendEmailService

@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    邮件内容
     */
    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()方法需要接收的参数除了基本的发送信息外,还包括静态资源唯一标识、静态资源路径和附件路径
    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  邮件内容
     */
    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();
        }
    }



}

四、邮箱配置POP3/SMTP服务

1:在账户中查看POP3/SMTP服务是否开启

2:获取授权码(password)

五、邮件发送+定时任务

注意:开启定时任务:

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

2:在相应的service层上加上注解@Scheduled

@Service
class sendSimpleMailTest {

    @Autowired
    private SendEmailService sendEmailService;
    @Autowired
    private TemplateEngine templateEngine;
    /**
     *发送文本邮件
     */
    @Scheduled(cron = "0 0 */1 * * ?")//会每隔一个小时点立即执行
    public void sendSimpleMailTest() {
        String to="123456789@qq.com";//这里修改为你能接收到的邮箱
        String subject="【纯文本邮件】标题";
        String text="Spring Boot纯文本邮件发送内容测试.....";
        // 发送简单邮件
        sendEmailService.sendSimpleEmail(to,subject,text);
    }
    @Scheduled(cron = "0 0 */1 * * ?")//会每隔一个小时点立即执行
    public void sendComplexEmailTest() {
        //根据前面定义的复杂邮件发送业务定制各种参数
        String to="123456789@qq.com";//修改为你自己的邮件方便接收查看
        String subject="【复杂邮件】标题";
        // 定义邮件内容
        StringBuilder text = new StringBuilder();
        //对邮件内容使用了HTML标签编辑邮件内容
        text.append("<html><head></head>");
        text.append("<body><h1>祝大家元旦快乐!</h1>");
        // cid为嵌入静态资源文件关键字的固定写法,如果改变将无法识别;rscId则属于自定义的静态资源唯一标识,一个邮件内容中可能会包括多个静态资源,该属性是为了区别唯一性的。
        String rscId = "img001";
        text.append("<img src='cid:" +rscId+"'/></body>");
        text.append("</html>");
        // 指定静态资源文件和附件路径
        String rscPath="E:\\hello.jpg";//注意这里修改为你的硬盘中有的资源
        String filePath="E:\\sendmail.txt";//注意这里修改为你的硬盘中有的资源
        // 发送复杂邮件
        sendEmailService.sendComplexEmail(to,subject,text.toString(),filePath,rscId,rscPath);
    }
    @Scheduled(cron = "0 * * * * *")//会在整点分钟时间点立即执行
    public void sendTemplateEmailTest() {
        String to="123456789@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);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值