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

2019-04-17  本文已影响0人  蜜思1013
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring.mail.host=smtp.qq.com
spring.mail.username=2413890705@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
public interface MailService {
    /**
     * 发送简单邮件
     */
    void sendMail(String to,String subject,String content);

}
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("......@qq.com");//发起者
        mailMessage.setTo(".......@qq.com");//接受者
        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 00 08 ? * *")
    public void proces(){
        mailService.sendMail("......@qq.com","王欣雅","定时9.47发送");
        System.out.println("hello");
    }
}

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

上一篇 下一篇

猜你喜欢

热点阅读