StringBoot邮件的异步发送
1.在启动类中加个开启异步功能注解
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(CheckApplication.class, args);
}
}
2.创建异步调用类和方法
把邮件发送类注册成bean,加上@Service即可。
在该类上加上@EnableAsync,表示该类支持异步调用。
在对应异步方法上加上@Async注解。
@Service
@EnableAsync
public class SendMailUtil {
@Autowired
private JavaMailSenderImpl javaMailSender;
@Async
public void SEND_SUBMIT_EMAIL(String sendToAccount, String sendToName) {
//简易版邮件发送
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("邮件主题");
mailMessage.setText("文本内容");
mailMessage.setFrom("发件人邮箱号");
mailMessage.setTo("收件人邮箱号");
//发送
javaMailSender.send(mailMessage);
}
}
3.在Controller中调用异步方法即可
@Controller
@RequestMapping("/asyncController")
public class AsyncController extends BaseController {
//注入邮件类
@Autowired
private SendMailUtil sendMailUtil;
@RequestMapping(params = "async")
@ResponseBody
public Json async(HttpServletRequest request) {
//异步发送邮件
sendMailUtil.SEND_SUBMIT_EMAIL("-----------", "-----------");
System.out.println("Execute before sending mail!");
//在邮件发送之前就返回了
return j;
}
}