springtask定时发送邮件
开启设置
按照 打开QQ邮箱->设置->开启服务POP3/SMTP开启->获取授权码
添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=1729713807@qq.com
spring.mail.password=udmnwkaxeixofbae
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
第三行是开启的POP3的授权码 每个人都不一样
Service接口
public interface MailService {
void sendMail(String to,String subject,String content);
}
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("1062273622@qq.com");//发起者
mailMessage.setTo(to);//接受者
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
mailSender.send(mailMessage);
System.out.println("发送简单邮件");
}catch (Exception e){
System.out.println("发送简单邮件失败");
}
}
}
每15秒发送一份电子邮件
@Service
//@Async
public class TaskService {
@Autowired
private MailService mailService;
@Scheduled(cron = "*/15 * * * * ?")
public void proces(){
mailService.sendMail("86884571@qq.com","简单邮件","我是测试");
System.out.println("111");
}
}