Version: Next

邮件任务

导入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  • SpringBoot配置文件
# 新浪邮箱
spring.mail.host=smtp.sina.com # 邮箱主机,根据使用的邮箱厂商更换
spring.mail.username=soulmatexiaoyu@sina.com # 自己的邮箱地址
spring.mail.password= # 登陆邮箱手动开启POP3/SMTP后获得的遗传密码
spring.mail.port=465
spring.mail.protocol=smtps
  • Controller
@Component
class AsyncTask {
private JavaMailSenderImpl mailSender;
private MailSender sender;
private MailProperties mailProperties;
public AsyncTask(MailSender sender, MailProperties mailProperties, JavaMailSenderImpl mailSender) {
this.sender = sender;
this.mailProperties = mailProperties;
this.mailSender = mailSender;
}
@Async
public void sendMail(String address, String title, String content) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(mailProperties.getUsername());
mailMessage.setSubject(title);
mailMessage.setTo(address);
mailMessage.setText(content);
sender.send(mailMessage);
System.out.println("异步发送邮件函数");
}
@Async
public void sendComplexMail(String address, String title, String content) throws MessagingException {
//邮件设置2:一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(title);
helper.setText(content);
//发送附件
helper.addAttachment("1.jpg", new File(""));
helper.addAttachment("2.jpg", new File(""));
helper.setTo(address);
helper.setFrom(mailProperties.getUsername());
mailSender.send(mimeMessage);
}
}
// ---------------------------------------------------------------
@Controller
@RequestMapping("/mail")
public class MailController {
private MailSender sender;
private MailProperties mailProperties;
private AsyncTask asyncTask;
public MailController(MailSender sender, MailProperties mailProperties, AsyncTask asyncTask) {
this.sender = sender;
this.mailProperties = mailProperties;
this.asyncTask = asyncTask;
}
@GetMapping("/index")
public ModelAndView index() {
return new ModelAndView("mail/index");
}
public void sendMail(String address, String title, String content) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(mailProperties.getUsername());
mailMessage.setSubject(title);
mailMessage.setTo(address);
mailMessage.setText(content);
sender.send(mailMessage);
}
//同步发送邮件
@GetMapping("/send")
public ModelAndView send(String address, String title, String content) {
this.sendMail(address, title, content);
return new ModelAndView("/mail/index");
}
//异步发送邮件
@ResponseBody
@PostMapping("/send/async")
public String sendAsync(String address, String title, String content) {
asyncTask.sendMail(address, title, content);
System.out.println("发送邮件完毕");
return "发送成功";
}
}
  • 在启动程序上加@EnableAsync
@EnableAsync
@SpringBootApplication
public class Springboot08EmailApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08EmailApplication.class, args);
}
}