8.使用spring task方法實現(xiàn)定時發(fā)送簡單郵件

  • 首先配置QQ郵箱->設(shè)置->賬戶->開啟服務POP3/SMTP開啟->獲取授權(quán)碼

    image
  • 添加依賴

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

  • 配置application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=2324407028@qq.com  
##授權(quán)碼
spring.mail.password=dpupddbvxgjddjai
spring.mail.default-encoding=UTF-8

##如果不加下面3句,會報530錯誤
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

  • Service接口
public interface MailService {
    /**
     * 發(fā)送簡單郵件
     */
    void sendMail(String to,String subject,String content);

}

  • 實現(xiàn)Service接口
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;
    @Override
    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setFrom("2324407028@qq.com");//發(fā)起者
        mailMessage.setTo("1599592024@qq.com");//接受者
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        try {
            mailSender.send(mailMessage);
            System.out.println("發(fā)送郵件成功");
        }catch (Exception e){
            System.out.println("發(fā)送郵件失敗");
        }
    }
}

  • 寫定時任務
package com.soft1721.jianyue.api.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
//@Async
public class TaskService {
    @Autowired
    private MailService mailService;

    @Scheduled(cron = "0 47 09 ? * *")
    public void proces(){
        mailService.sendMail("1599592024@qq.com","王欣雅","定時9.47發(fā)送");
        System.out.println("hello");
    }
}

icon表達式http://www.itdecent.cn/p/2abe2fe4ad32

  • 運行結(jié)果

    image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容