在Spring Boot的工程中的pom.xml
中引入spring-boot-starter-mail 依賴包:html
<dependencies> <dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency> </dependencies>
在 application.properties 中添加郵箱配置,不一樣的郵箱參數稍有不一樣,下面列舉一個經常使用郵箱配置。spring
163 郵箱配置:服務器
spring.mail.host=smtp.163.com //郵箱服務器地址
spring.mail.username=xxx@oo.com //⽤戶名
spring.mail.password=xxyyooo //密碼
spring.mail.default-encoding=UTF-8
//超時時間,可選
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
JavaMailSender
Spirng 已經幫咱們內置了 JavaMailSender,直接在項目中引用便可。併發
1、咱們封裝一個 MailService 類來實現普通的郵件發送方法。app
@Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String from; @Override public void sendSimpleMail(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); logger.info("簡單郵件已經發送。"); } catch (Exception e) { logger.error("發送簡單郵件時發生異常!", e); } }
}
from,即爲郵件發送者;
to,郵件接收者;
subject,郵件主題;
content,郵件的主體。
郵件發送者 from 通常採用固定的形式寫到配置文件中(配置文件自定義以前已有介紹),也能夠直接寫發送者郵箱。ide
編寫 test 類進行測試spring-boot
@RunWith(SpringRunner.class) @Spring BootTest public class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { mailService.sendSimpleMail("****@126.com","這是一封簡單郵件","⼤家好,這是個人第一封郵件!"); } }
2、富文本郵件學習
在平常使用的過程當中,咱們一般在郵件中加入圖片或者附件來豐富郵件的內容,下面將介紹如何使用 Spring Boot 來發送富文本郵件。測試
1)發送 HTML 格式郵件this
/** * 發送html郵件 * @param to * @param subject * @param content */ @Override public void sendHtmlMail(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); logger.info("html郵件發送成功"); } catch (MessagingException e) { logger.error("發送html郵件時發生異常!", e); } }
MimeMessageHelper 支持發送複雜郵件模板, 支持文本、附件、HTML、圖片等,接下來咱們會繼續使用。
在測試類中構建 HTML 內容,測試發送:
@Test public void testHtmlMail() throws Exception { String content="<html>\n" + "<body>\n" + " <h3>hello world ! 這是⼀封html郵件!</h3>\n" + "</body>\n" + "</html>"; mailService.sendHtmlMail("ityouknow@126.com","這是一封HTML郵件",content); }
2)發送帶附件的郵件
在 MailService 添加 sendAttachmentsMail 方法。
public void sendAttachmentsMail(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 = file.getFilename(); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("帶附件的郵件已經發送。"); } catch (MessagingException e) { logger.error("發送帶附件的郵件時發生異常!", e); } }
測試方法:
@Test public void sendAttachmentsMail() { String filePath="E:\\學習資料\\W3C\\jdk150.ZH_cn.chm"; mailService.sendAttachmentsMail("peng.li@rongdatech.com", "主題:帶附件的郵件", "有附件,請查收!", filePath); }
3)發送帶靜態資源的郵件
郵件中的靜態資源通常就是指圖片,在 MailService 添加 sendAttachmentsMail 方法。
/** * 發送正文中有靜態資源(圖片)的郵件 * @param to * @param subject * @param content * @param rscPath * @param rscId */ public void sendInlineResourceMail(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); logger.info("嵌入靜態資源的郵件已經發送。"); } catch (MessagingException e) { logger.error("發送嵌入靜態資源的郵件時發生異常!", e); } }
測試方法:
@Test public void sendInlineResourceMail() { String rscId = "CES"; String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>"; String imgPath = "e:\\CES.jpg"; mailService.sendInlineResourceMail("peng.li@rongdatech.com", "主題:這是有圖片的郵件", content, imgPath, rscId); }
上面發送郵件的基礎服務就這些了,可是若是咱們要作成一個郵件系統的話還須要考慮如下幾個問題。
郵件模板
咱們會常常收到這樣的郵件:
其中只有 neo 這個用戶名在變化,其餘郵件內容均不變,若是每次發送郵件都須要改動拼接不夠優雅,而且 每次模板的修改都須要改動代碼很是不方便,所以對於這類郵件需求,都建議作成郵件模板來處理。模板的 本質很簡單,就是在模板中替換變化的參數,轉換爲 HTML 字符串便可,這裏以 thymeleaf 爲例來演 示。
pom 中導入 thymeleaf 的包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在 resorces/templates 下建立 emailTemplate.html
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>郵件模板</title> </head> <body> 您好,感謝您的註冊,這是⼀封驗證郵件,請點擊下⾯的連接完成註冊,感謝您的⽀持<br/>
<a href="#" th:href="@{http://www.****.com/register/{id}(id=${id}) }" >激活帳號</a> </body> </html>
解析模板併發送
@Test public void sendTemplateMail() { //建立郵件正文 Context context = new Context(); context.setVariable("id", "001"); String emailContent = templateEngine.process("emailTemplate", context); mailService.sendHtmlMail("peng.li@rongdatech.com","主題:這是模板郵件",emailContent); }