Springboot2(21)輕鬆整合mail
阿新 • • 發佈:2018-12-29
SpringBoot實現郵件功能是非常的方便快捷的,因為SpringBoot預設有starter實現了Mail。 傳送郵件應該是網站的必備功能之一,什麼註冊驗證,忘記密碼或者是給使用者傳送營銷資訊。 最早期的時候我們會使用JavaMail相關api來寫傳送郵件的相關程式碼,後來spring退出了 JavaMailSender更加簡化了郵件傳送的過程,在之後springboot對此進行了封裝就有了 現在的spring-boot-starter-mail。
文章目錄
基礎配置
引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- 模板引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
獲取QQ郵箱授權碼
QQ郵箱->設定->賬戶->POP3/SMTP服務:開啟服務後會獲得QQ的授權碼.
Mail配置檔案
# JavaMailSender 郵件傳送的配置 spring.mail.host: smtp.qq.com spring.mail.username: 使用者qq郵箱 #QQ郵箱的授權碼 spring.mail.password: 授權碼 spring.mail.properties.mail.smtp.auth: true spring.mail.properties.mail.smtp.starttls.enable: true spring.mail.properties.mail.smtp.starttls.required: true spring.mail.default-encoding: UTF-8
163郵箱配置
#郵箱伺服器地址
spring.mail.host: smtp.***.cn
#使用者名稱
spring.mail.username: ****@****.cn
#密碼
spring.mail.password: *****
spring.mail.default-encoding: UTF-8
spring.mail.sendTo: *****@qq.com
實現過程
@Component
@Slf4j
public class MailServiceImp implements MailService{
@Autowired
private JavaMailSender mailSender;
@Override
public void sendSimpleMail(String from,String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
/**
* 傳送html郵件
* @param to
* @param subject
* @param content
*/
@Override
public void sendHtmlMail(String from,String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要建立一個multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
log.info("html郵件傳送成功");
} catch (MessagingException e) {
log.error("傳送html郵件時發生異常!", e);
}
}
/**
* 傳送帶附件的郵件
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String from,String to, String subject, String content, String filePath){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);
mailSender.send(message);
log.info("帶附件的郵件已經發送。");
} catch (MessagingException e) {
log.error("傳送帶附件的郵件時發生異常!", e);
}
}
/**
* 傳送正文中有靜態資源(圖片)的郵件
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
*/
public void sendInlineResourceMail(String from,String to, String subject, String content, String rscPath, String rscId){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
log.info("嵌入靜態資源的郵件已經發送。");
} catch (MessagingException e) {
log.error("傳送嵌入靜態資源的郵件時發生異常!", e);
}
}
}
在resorces/templates下建立MailTemplate.html.html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
您好,這是驗證郵件,請點選下面的連結完成驗證,<br/>
<a href="#" th:href="@{ http://www.rojao.com/n/{id}(id=${id}) }">啟用賬號</a>
</body>
</html>
傳送郵件
@RestController
public class MainController {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.sendTo}")
private String sendTo;
@RequestMapping("/send")
public String send(){
sendSimpleMail();
return "success";
}
public void sendSimpleMail(){
mailService.sendSimpleMail(from,sendTo,"這是一封測試郵件!","這是一封測試郵件!");
}
public void sendHtmlMail() throws Exception {
String content="<html>\n" +
"<body>\n" +
" <h3>hello world ! 這是一封html郵件!</h3>\n" +
"</body>\n" +
"</html>";
mailService.sendHtmlMail(from,sendTo,"test simple mail",content);
}
public void sendAttachmentsMail() {
String filePath="e:\\tmp\\application.log";
mailService.sendAttachmentsMail(from,sendTo, "主題:帶附件的郵件", "有附件,請查收!", filePath);
}
public void sendInlineResourceMail() {
String rscId = "neo006";
String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>";
String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png";
mailService.sendInlineResourceMail(from,sendTo,"主題:這是有圖片的郵件", content, imgPath, rscId);
}
public void sendTemplateMail() {
//建立郵件正文
Context context = new Context();
context.setVariable("id", "006");
String emailContent = templateEngine.process("MailTemplate", context);
mailService.sendHtmlMail(from,sendTo,"主題:這是模板郵件",emailContent);
}
}
郵件非同步傳送
很多時候郵件傳送並不是我們主業務必須關注的結果,比如通知類、提醒類的業務可以允許延時或者失敗。
這個時候可以採用非同步的方式來發送郵件,加快主交易執行速度,在實際專案中可以採用MQ傳送郵件相關
引數,監聽到訊息佇列之後啟動傳送郵件