首先配置QQ郵箱->設(shè)置->賬戶->開啟服務POP3/SMTP開啟->獲取授權(quán)碼
添加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=1062273622@qq.com
spring.mail.password=amujxrblfdyobeeh
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
寫Service接口
public interfaceMailService {
/**
* 發(fā)送簡單郵件
*/
void sendMail(String to,String subject,Stringcontent);
}
實現(xiàn)接口
@Service("mailService")
public class MailServiceImpl implements MailService{
@Autowired
privateJavaMailSender mailSender;
@Override
public void sendMail(String to, String subject, Stringcontent) {
SimpleMailMessage mailMessage=newSimpleMailMessage();
mailMessage.setFrom("1062273622@qq.com");//發(fā)起者
mailMessage.setTo(to);//接受者
mailMessage.setSubject(subject);
mailMessage.setText(content);
try{
mailSender.send(mailMessage);
System.out.println("發(fā)送簡單郵件");
}catch(Exception e){
System.out.println("發(fā)送簡單郵件失敗");
}
}
}
寫定時任務:每六秒發(fā)送一份電子郵件
@Service
//@Async
public class TaskService{
@Autowired
privateMailService mailService;
@Scheduled(cron = "*/6 * * * * ?")
public void proces(){
mailService.sendMail("815835155@qq.com","簡單郵件","lalalalalalalaal");
System.out.println("111");
}
}