spring boot集成spring-boot-starter-mail郵件功能
- 2020 年 6 月 19 日
- 筆記
- springboot
Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。總之就是springboot 真香
相信使用過Spring的眾多開發者都知道Spring提供了非常好用的JavaMailSender
介面實現郵件發送。在Spring Boot的Starter模組中也為此提供了自動化配置。下面通過實例看看如何在Spring Boot中使用JavaMailSender
發送郵件。
1.使用普通的maven項目需要加入spring-context-support依賴,因為JavaMailSenderImpl類在這個包下面:
2.使用springboot 需要引入
<!-- email --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
依賴引入之後 在我們的配置文件中做如下配置
注意這裡面的密碼是我們郵箱的授權碼 不是登陸的密碼
另外有上傳到伺服器中報錯無法使用的 比如阿里雲 騰訊雲
以騰訊云為例 可以申請去解封25埠 百度很多方法。在這隻提一下這個問題
在本部落格只演示的發送郵件和附件
/** * 無附件 簡單文本內容發送 * @param email 接收方email * @param subject 郵件內容主題 * @param text 郵件內容 */ public void simpleMailSend(String email,String subject,String text) { //創建郵件內容 SimpleMailMessage message=new SimpleMailMessage(); message.setFrom(username);//這裡指的是發送者的帳號 message.setTo(email); message.setSubject(subject); message.setText(text); //發送郵件 mailSender.send(message); System.out.println("\033[32;1m"+"發送給 "+email+" 的郵件發送成功"+"\033[0m"); }
/** * 發送帶附件的郵件 * * @param to 接受人 * @param subject 主題 * @param html 發送內容 * @param filePath 附件路徑 * @throws MessagingException 異常 * @throws UnsupportedEncodingException 異常 */ public void sendAttachmentMail(String to, String subject, String html, String filePath) throws MessagingException, UnsupportedEncodingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); // 設置utf-8或GBK編碼,否則郵件會有亂碼 MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); messageHelper.setFrom(username,emailName); messageHelper.setTo(to); messageHelper.setSubject(subject); messageHelper.setText(html, true); FileSystemResource file=new FileSystemResource(new File(filePath)); String fileName=filePath.substring(filePath.lastIndexOf(File.separator)); messageHelper.addAttachment(fileName,file); mailSender.send(mimeMessage); }
/** * 發送html內容的 郵件 * @param email * @param subject * @param text */ public void sendSimpleMailHtml(String email,String subject,String text) throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(username); helper.setTo("[email protected]"); helper.setSubject("主題:嵌入靜態資源"); // 注意<img/>標籤,src='cid:jpg','cid'是contentId的縮寫,'jpg'是一個標記 helper.setText("<html><body><img src=\"cid:jpg\"></body></html>", true); // 載入文件資源,作為附件 FileSystemResource file = new FileSystemResource(new File("C:\\Users\\吳超\\Pictures\\Camera Roll\\微信截圖_20191016142536.png")); // 調用MimeMessageHelper的addInline方法替代成文件('jpg[標記]', file[文件]) helper.addInline("jpg", file); // 發送郵件 mailSender.send(mimeMessage); }
打開我們的郵箱 小姐姐到手