1.获取授权码
首先打开QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码
image- 打开服务,需要发送短信的,然后获取授权码
2.添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.配置application.properties
###邮箱配置
spring.mail.host=smtp.qq.com
spring.mail.username=******* //这里填写你的邮箱
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
4.service接口
public interface MailService {
/**
* 发送简单邮件
*/
void sendMail(String to,String subject,String content);
}
5.实现接口
@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("*********");//发起者的邮箱
mailMessage.setTo("**********");//接受者的邮箱
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
mailSender.send(mailMessage);
System.out.println("发送简单邮件");
}catch (Exception e){
System.out.println("发送简单邮件失败");
}
}
}
6.写定时任务
@Service
//@Async
public class TaskService {
@Autowired
private MailService mailService;
@Scheduled(cron = "0 01 10 ? * *") //这是cron表达式
public void proces(){
mailService.sendMail("123456qq.com","标题","内容"); //一是接受者的邮箱,二是邮件的标题 三是邮件的内容
System.out.println("111");
}
}
7.最后启动主类
运行结果
image
网友评论