day09 基于spring的定时任务发送邮件

2019-04-18  本文已影响0人  山下_26

1.定时任务实现的几种方式:

2.使用spring task发送定时邮件

需要用到的maven依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
application.properties配置
##qq邮箱配置
spring.mail.host=smtp.qq.com
spring.mail.username=xxxxxxxxxx@qq.com
spring.mail.password=授权码
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
MailService接口
public interface MailService {
    /**
     * 发送简单邮件
     */
    void sendMail(String to,String subject,String content);
}

MailServiceImpl
@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("xxx");//发起者
        mailMessage.setTo("xxx");//接收者
        mailMessage.setSubject("定时邮件测试");
        mailMessage.setText("这是一个定时邮件测试");
        try {
            mailSender.send(mailMessage);
            System.out.println("发送简单邮件");
        }catch (Exception e){
            System.out.println("发送简单邮件失败");
        }
    }

}
TaskService
@Service
public class TaskService {
    @Autowired
    private MailService mailService;

     //cron时间表达式
    @Scheduled(cron = "0 8 10 ? * *")
    public void proces(){
        mailService.sendMail("xxx","定时邮件测试","这是一个定时邮件测试");
        System.out.println("success");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读