18-springtask之邮件发送


首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码

添加pom依赖

<dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-mailartifactId>

dependency>

配置application.properties

spring.mail.host=smtp.qq.com

[email protected]

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 {

/**

* 发送简单邮件

*/

void sendMail(String to,String subject,Stringcontent);


}

实现接口

@Service("mailService")

public class MailServiceImpl implements MailService{

@Autowired

privateJavaMailSender mailSender;


@Override

public void sendMail(String to, String subject, Stringcontent) {

SimpleMailMessage mailMessage=newSimpleMailMessage();

mailMessage.setFrom("[email protected]");//发起者

mailMessage.setTo(to);//接受者

mailMessage.setSubject(subject);

mailMessage.setText(content);

try{

mailSender.send(mailMessage);

System.out.println("发送简单邮件");

}catch(Exception e){

System.out.println("发送简单邮件失败");

}

}



}

写定时任务:每六秒发送一份电子邮件

@Service

//@Async

public class TaskService{

@Autowired

privateMailService mailService;

@Scheduled(cron = "*/6 * * * * ?")

public void proces(){

mailService.sendMail("[email protected]","简单邮件","lalalalalalalaal");

System.out.println("111");

}

}

你可能感兴趣的:(18-springtask之邮件发送)