1.首先配置QQ邮箱->设置->账户->开启服务POP3/SMTP开启->获取授权码
2.在pom.xml中添加依赖
<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=824772535@qq.com //自己的邮箱地址
spring.mail.password=fvbiwufrqsfbbcbc //开启时获取的授权码
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.写实现接口
import com.soft1721.jianyue.api.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@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("824772535@qq.com");//发起者
mailMessage.setTo("16422802@qq.com");//接受者
mailMessage.setSubject("朱芮林");//标题
mailMessage.setText("abcdefghijklmnopqrstuvwxyz 9:50发送");//发送的邮件内容
try {
mailSender.send(mailMessage);
System.out.println("发送简单邮件");
}catch (Exception e){
System.out.println("发送简单邮件失败");
}
}
}
6.写定时任务
import com.soft1721.jianyue.api.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
//@Async
public class TaskService {
@Autowired
private MailService mailService;
@Scheduled(cron = "0 50 9 ? * MON") //corn表达式:定时为每周一早上9:50发送,可更换
public void proces(){
mailService.sendMail("16422802@qq.com","朱芮林","abcdefghijklmnopqrstuvwxyz 9:50发送");
System.out.println("发送成功");
}
}
corn表达式详解