1.獲取授權碼
首先打開QQ郵箱->設置->賬戶->開啟服務POP3/SMTP開啟->獲取授權碼
- 打開服務又活,需要發(fā)送短信的喜鼓,然后獲取授權碼
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 {
/**
* 發(fā)送簡單郵件
*/
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("*********");//發(fā)起者的郵箱
mailMessage.setTo("**********");//接受者的郵箱
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
mailSender.send(mailMessage);
System.out.println("發(fā)送簡單郵件");
}catch (Exception e){
System.out.println("發(fā)送簡單郵件失敗");
}
}
}
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.最后啟動主類
運行結果