1、在pom.xml中引入邮件发送相关依赖
<!--邮件发送依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、依赖添加成功后,在application.yml中配置邮件
#邮件配置
spring:
mail:
host: smtp.qq.com
port: 465
username:
password:
default-encoding: UTF-8
properties:
mail:
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
debug: true
3、创建邮件工具类MailUtils
@Component
public class MailUtils {
@Autowired
private JavaMailSenderImpl mailConfig;
@Value("1130371017@qq.com")
private String mailfrom;
public void sendSimpleEmail(String mailto,String title,String content){
//定制邮件发送内容
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(mailfrom);
message.setTo(mailto);
message.setSubject(title);
message.setText(content);
//发送邮件
mailConfig.send(message);
}
}
5、邮件定时发送调度实现
@Component
public class ScheduleTask {
@Autowired
private MailUtils mailUtils;
@Value("1130371017@qq.com")
private String mailto;
//定时邮件发送任务
@Scheduled(cron = "0 */3 * * * ?")
public void sendEmail(){
//定制邮件内容
mailUtils.sendSimpleEmail(mailto,"值班通知","请于明日前往公司值班");
}
}
6、开启基于注解的定时任务,在启动类上加入注解@EnableScheduling
运行报错:
springboot Got bad greeting from SMTP host: smtp.qq.com, port: 465, response: [EOF]
解决办法:如果使用端口为465
,将protocol的smtp
改为smtps
将配置文件端口改为587
,则可以使用smtp。