使用spring task方法实现定时发送简单邮件

  • 首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码

    image
  • 添加依赖


   org.springframework.boot
   spring-boot-starter-mail


  • 配置application.properties
spring.mail.host=smtp.qq.com
[email protected]  
##授权码
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 {
    /**
     * 发送简单邮件
     */
    void sendMail(String to,String subject,String content);

}

  • 实现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("[email protected]");//发起者
        mailMessage.setTo("[email protected]");//接受者
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        try {
            mailSender.send(mailMessage);
            System.out.println("发送邮件成功");
        }catch (Exception e){
            System.out.println("发送邮件失败");
        }
    }
}

  • 写定时任务
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("[email protected]","shitou","定时9.40发送");
        System.out.println("hello");
    }
}

icon表达式https://www.jianshu.com/p/2abe2fe4ad32

  • 运行结果

    image

你可能感兴趣的:(使用spring task方法实现定时发送简单邮件)