SpringBoot使用定時任務發送郵件


一、導入jar包

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

二、在application.properties種添加郵箱配置

QQ郵箱需要設置開啟smtp服務,具體的請查詢一下如何開啟,此處省略

spring.mail.host=smtp.qq.com
spring.mail.username=54281****@qq.com
spring.mail.password=tneawbzduhvf****
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

三、發送郵件類

package com.example.demo.timedtask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Scheduler2Task {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Autowired
    private JavaMailSender mailSender;

    /*
     * @Scheduled(fixedRate = 6000) 上一次開始執行時間點之后6秒再執行
     * @Scheduled(fixedDelay = 6000) 上一次執行完畢時間之后6秒再執行
     * @Scheduled(initialDelay=1000, fixedRate=6000) 第一次延遲1秒后執行,之后按fixedRate的規則執行
     * */
    @Scheduled(fixedRate = 6000)/*每隔六秒鍾執行一次*/
    public void reportCurrentTime() {
        System.out.println("現在時間:" + dateFormat.format(new Date()));
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("542813934@qq.com");
        message.setTo("542813934@qq.com");
        message.setSubject("主題:簡單郵件1");
        message.setText("測試郵件內容1");
        mailSender.send(message);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM