實現郵件傳送
- 匯入mail依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 配置application, qq授權碼必須是傳送者qq的授權碼,獲取方式很簡單, 百度有詳細步驟
spring.mail.username=321359027@qq.com
# password是qq授權碼
spring.mail.password=XXXXXXX
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
- 編寫傳送程式碼
- 由於SprigBoot的自動配置以及幫我們註冊了JavaMailSenderImpl的Bean, 所以我們可以直接使用它
@Service
public class MailService {
@Autowired
private JavaMailSenderImpl sender;
public void sendSimpleMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("XXXXXX@qq.com");
simpleMailMessage.setTo("XXXXXX@qq.com");
simpleMailMessage.setSubject("緊急通知");
simpleMailMessage.setText("開個玩笑,哈哈哈");
sender.send(simpleMailMessage);
System.out.println("[DEBUG]" + simpleMailMessage.getSubject() + ",傳送成功");
}
public void sendMimeMessage() throws MessagingException {
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setSubject("爽娃娃");
mimeMessageHelper.setText("<h style='color:red'></h>", true);
mimeMessageHelper.addAttachment("小哥哥好壞.png",
new File("C:\\Users\\Huawei\\Desktop\\QQ截圖20201118160318.png"));
mimeMessageHelper.setFrom("XXXXXX@qq.com");
mimeMessageHelper.setTo("XXXXXX@qq.com");
sender.send(mimeMessage);
System.out.println("[DEBUG]" + mimeMessage.getSubject() + ",傳送成功");
}
}
- 編寫controller訪問
@RestController
public class MailController {
@Autowired
private MailService service;
@RequestMapping("/send")
public String send() {
System.out.println("開始傳送時間:" + new Date().toString());
service.sendSimpleMessage();
System.out.println("返回響應時間:" + new Date().toString());
return "Send OK";
}
@RequestMapping("/send2")
public String send2() {
System.out.println("開始傳送時間:" + new Date().toString());
try {
service.sendMimeMessage();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("返回響應時間:" + new Date().toString());
return "Send OK";
}
}
- 測試, 執行專案, 訪問路徑controller
- 郵件傳送成功, 但是我們通過DEBUG的時間發現耗時太長
- 我們使用非同步任務對其進行優化
實現使用非同步任務優化郵件傳送
- 開啟非同步任務 @EnableAsync //開啟非同步任務
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 在傳送郵件的方法上新增註解 @Async
@Async
public void sendSimpleMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("321359027@qq.com");
simpleMailMessage.setTo("1604053140@qq.com");
simpleMailMessage.setSubject("緊急通知");
simpleMailMessage.setText("開個玩笑,哈哈哈");
sender.send(simpleMailMessage);
System.out.println("[DEBUG]" + simpleMailMessage.getSubject() + ",傳送成功");
}
- 再次測試訪問
- 這次郵件正常傳送, 並且提高了使用者體驗
- 在我們的工作中,常常會用到非同步處理任務,比如我們在網站上傳送郵件,後臺會去傳送郵件,此時前臺會造成響應不動,直到郵件傳送完畢,響應才會成功,所以我們一般會採用多執行緒的方式去處理這些任務。還有一些定時任務,比如需要在每天凌晨的時候,分析一次前一天的日誌資訊。還有就是郵件的傳送,SpringBoot都給我們提供了對應的支援,我們上手使用十分的簡單,只需要開啟一些註解支援,配置一些配置檔案即可!