Spring boot 發送郵箱

一、簡介

????????Spring 提供了非常好用的 JavaMailSender 接口實現郵件發送。在 SpringBoot 的 Starter 模塊中也為此提供了自動化配置。下面通過實例看看如何在 SpringBoot 中使用 JavaMailSender 發送郵件。

?org.springframework.mail 是Spring Framework對郵件支持的基礎包,發送郵件的核心接口MailSender,SimpleMailMessage封裝了發送簡單郵件的屬性 ,這個包還包含檢查異常的層次結構,這些層次結構在較低級別的郵件系統異常上提供了更高級別的抽象,而根異常是MailException

org.springframework.mail.javamail.JavaMailSender接口添加了專門的JavaMail功能,例如MIME消息支持到MailSender接口 (從其繼承)。JavaMailSender還提供了一個名為org.springframework.mail.javamail.MimeMessagePreparator的回調接口,用于準備一個MimeMessage。

二、使用 SpringBoot 創建 Java Web 項目,添加郵件相關依賴包

??在 SpringBoot 工程中的 pom.xml 中引入 spring-boot-starter-mail 依賴。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>

三、使用

假設我們有一個名為OrderManager的業務類,如下面的示例所示:

public interface OrderManager {void placeOrder(Order order) throws MessagingException;
}

3、1MailSender和SimpleMailMessage的基本用法

public class SimpleOrderManager implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate MailSender mailSender;public void placeOrder(Order order) {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itSimpleMailMessage msg = new SimpleMailMessage();msg.setTo(order.getCustomer().getEmailAddress());msg.setFrom(mailFrom);msg.setText("Dear " + order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());try {this.mailSender.send(msg);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}}

3.2 JavaMailSender 和MimeMessagePreparator的用法

@Service
public class SimpleOrderManagerPreparator implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void setMailSender(JavaMailSender mailSender) {this.mailSender = mailSender;}@Overridepublic void placeOrder(final Order order) {// Do the business calculations...// Call the collaborators to persist the order...MimeMessagePreparator preparator = new MimeMessagePreparator() {public void prepare(MimeMessage mimeMessage) throws Exception {mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(order.getCustomer().getEmailAddress()));mimeMessage.setFrom(new InternetAddress(mailFrom));mimeMessage.setText("Dear " + order.getCustomer().getFirstName() + " " +order.getCustomer().getLastName() + ", thanks for your order. " +"Your order number is " + order.getOrderNumber() + ".");}};try {this.mailSender.send(preparator);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}}

郵件代碼可以作為一個切面,可以在OrderManager目標上的適當連接點處運行。

3.3 JavaMail MimeMessageHelper的使用

使用MimeMessageHelper可以代替基礎的JavaMail API。

@Service
public class SimpleOrderManagerHelper  implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("Dear " + order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}

3.4 發送附件

下面的示例將展示如何使用MimeMessageHelper發送帶有單個JPEG圖像附件的電子郵件:

@Service
public class SimpleOrderManagerAttachments implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("Check out this image!");// let's attach the infamous windows Sample file (this time copied to c:/)FileSystemResource file = new FileSystemResource(new File("./sample.png"));helper.addAttachment("CoolImage.jpg", file);try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}
發送附件和內聯資源
多部分電子郵件消息允許附件和內聯資源。內聯資源的示例包括要在郵件中使用但不想顯示為附件的圖像或樣式表。
附件
下面的示例向您展示如何使用MimeMessageHelper發送帶有單個JPEG圖像附件的電子郵件:

3.5 內聯資源

下面的示例將展示如何使用MimeMessageHelper發送帶有內聯映像的電子郵件:

@Service
public class SimpleOrderManagerInlineResources implements OrderManager {@Value("${spring.mail.from}")private String mailFrom;@Resourceprivate JavaMailSender mailSender;public void placeOrder(Order order) throws MessagingException {// Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize itMimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setTo(order.getCustomer().getEmailAddress());helper.setFrom(mailFrom);helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);// let's attach the infamous windows Sample file (this time copied to c:/)FileSystemResource res = new FileSystemResource(new File("./sample.png"));helper.addInline("identifier1234", res);try {this.mailSender.send(message);} catch (MailException ex) {// simply log it and go on...System.err.println(ex.getMessage());}}
}

????????通過使用指定的Content-ID 將內聯資源添加到MimeMessage。添加文本和資源的順序非常重要。請務必先添加文本,然后再添加資源。如果您以相反的方式進行操作,則無法正常工作。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/212908.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/212908.shtml
英文地址,請注明出處:http://en.pswp.cn/news/212908.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

云計算大屏,可視化云計算分析平臺(云實時數據大屏PSD源文件)

大屏組件可以讓UI設計師的工作更加便捷&#xff0c;使其更高效快速的完成設計任務。現分享可視化云分析系統、可視化云計算分析平臺、云實時數據大屏的大屏Photoshop源文件&#xff0c;開箱即用&#xff01; 若需 更多行業 相關的大屏&#xff0c;請移步小7的另一篇文章&#…

mapstruct個人學習記錄

mapstruct核心技術學習 簡介入門案例maven依賴 IDEA插件單一對象轉換測試結果 mapping屬性Spring注入的方式測試 集合的映射set類型的映射測試map類型的映射測試 MapMappingkeyDateFormatvalueDateFormat 枚舉映射基礎入門 簡介 在工作中&#xff0c;我們經常要進行各種對象之…

非標識性參數—手機運營商

2.2 非標識性參數 2.2.1 手機運營商 IMSI&#xff1a; 國際移動用戶識別碼&#xff0c;共有15位&#xff0c;儲存在SIM卡中&#xff0c;由MCC、MNC&#xff0c;MSIN組成。 MCC&#xff1a; (國家)移動國家號碼&#xff0c;由3位數字組成&#xff0c;唯一的識別移動客戶所屬的…

【rabbitMQ】rabbitMQ用戶,虛擬機地址(添加,修改,刪除操作)

rabbitMQ的下載&#xff0c;安裝和配置 https://blog.csdn.net/m0_67930426/article/details/134892759?spm1001.2014.3001.5502 rabbitMQ控制臺模擬收發消息 https://blog.csdn.net/m0_67930426/article/details/134904365?spm1001.2014.3001.5502 目錄 用戶 添加用戶…

MyBatis 四大核心組件之 StatementHandler 源碼解析

&#x1f680; 作者主頁&#xff1a; 有來技術 &#x1f525; 開源項目&#xff1a; youlai-mall &#x1f343; vue3-element-admin &#x1f343; youlai-boot &#x1f33a; 倉庫主頁&#xff1a; Gitee &#x1f4ab; Github &#x1f4ab; GitCode &#x1f496; 歡迎點贊…

CPU設計——Triumphcore——MP_work版本

該版本用作系統寄存器的實現&#xff0c;M/S/U狀態的實現與切換&#xff0c;以及load/store的虛實地址轉換 設計指標 2023.12.8 2023.12.9 不實現mideleg和medeleg&#xff0c;因此一旦出現異常&#xff0c;直接切換至M態&#xff0c; 調試記錄 到存儲區中取PTE要額外至少…

airserver mac 7.27官方破解版2024最新安裝激活圖文教程

airserver mac 7.27官方破解版是一款好用的airplay投屏工具&#xff0c;可以輕松將ios熒幕鏡像&#xff08;airplay&#xff09;至mac上&#xff0c;在mac平臺上實現視頻、音頻、幻燈片等文件資源的接收及投放演示操作&#xff0c;解決iphone或ipad的屏幕錄像問題&#xff0c;滿…

SpringBootAdmin設置郵件通知

如果你想要在Spring Boot Admin中配置郵件通知&#xff0c;可以按照以下步驟進行操作&#xff1a; 添加郵件通知的依賴 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId> </dep…

Linux C/C++ 從內存轉儲中恢復64位ELF可執行文件

ELF&#xff08;Executable and Linking Format&#xff09;是一種對象文件的格式&#xff0c;它主要用于定義ELF&#xff08;Executable and Linking Format&#xff09;是一種對象文件的格式&#xff0c;它主要用于定義不同類型的對象文件中的內容以及它們的存儲方式。一個EL…

作業調度算法(含詳細計算過程)和進程調度算法淺析

一.作業調度 作業調度算法需要知道以下公式 周轉時間完成時間 - 到達時間 帶權周轉時間周轉時間/運行時間 注&#xff1a;帶權周轉時間越大&#xff0c;作業&#xff08;或進程&#xff09;越短&#xff1b;帶權周轉時間越小&#xff0c;作業&#xff08;或進程&#xff09;越…

[git] 遠程刪除分支

[git] 遠程刪除分支 1. git刪除遠程分支 git push origin --delete [branch_name]2. 刪除本地分支區別 git branch -d 會在刪除前檢查merge狀態&#xff08;其與上游分支或者與head&#xff09;。git branch -D 是git branch --delete --force的簡寫&#xff0c;它會直接刪除…

Redis生產實戰-Redis集群故障探測以及降級方案設計

Redis 集群故障探測 在生產環境中&#xff0c;如果 Redis 集群崩潰了&#xff0c;那么會導致大量的請求打到數據庫中&#xff0c;會導致整個系統都崩潰&#xff0c;所以系統需要可以識別緩存故障&#xff0c;限流保護數據庫&#xff0c;并且啟動接口的降級機制 降級方案設計 …

《C++20設計模式》---原型模式學習筆記代碼

C20設計模式 第 4 章 原型模式學習筆記筆記代碼 第 4 章 原型模式 學習筆記 筆記代碼 #include<iostream> #include<string>// #define VALUE_OF_ADDRESS // PP_4_2_1 (no define: PP_4_2_2) namespace PP_4_2 {class Address{public:std::string street;std::st…

《C++20設計模式》學習筆記---原型模式

C20設計模式 第 4 章 原型模式4.1 對象構建4.2 普通拷貝4.3 通過拷貝構造函數進行拷貝4.4 “虛”構造函數4.5 序列化4.6 原型工廠4.7 總結4.8 代碼 第 4 章 原型模式 考慮一下我們日常使用的東西&#xff0c;比如汽車或手機。它們并不是從零開始設計的&#xff0c;相反&#x…

超過 50% 的內部攻擊使用特權提升漏洞

特權提升漏洞是企業內部人員在網絡上進行未經授權的活動時最常見的漏洞&#xff0c;無論是出于惡意目的還是以危險的方式下載有風險的工具。 Crowdstrike 根據 2021 年 1 月至 2023 年 4 月期間收集的數據發布的一份報告顯示&#xff0c;內部威脅正在上升&#xff0c;而利用權…

基于SSM的劇本殺預約系統的設計與實現

末尾獲取源碼 開發語言&#xff1a;Java Java開發工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 數據庫&#xff1a;MySQL5.7和Navicat管理工具結合 服務器&#xff1a;Tomcat8.5 開發軟件&#xff1a;IDEA / Eclipse 是否Maven項目&#xff1a;是 目錄…

【第三屆】:“玄鐵杯”RISC-V應用創新大賽(基于yolov5和OpenCv算法 — 智能警戒哨兵)

文章目錄 前言 一、智能警戒哨兵是什么&#xff1f; 二、方案流程圖 三、硬件方案 四、軟件方案 五、演示視頻鏈接 總結 前言 最近參加了第三屆“玄鐵杯”RISC-V應用創新大賽&#xff0c;我的創意題目是基于 yolov5和OpenCv算法 — 智能警戒哨兵 先介紹一下比賽&#xf…

docker容器配置MySQL與遠程連接設置(純步驟)

以下為ubuntu20.04環境&#xff0c;默認已安裝docker&#xff0c;沒安裝的網上隨便找個教程就好了 拉去mysql鏡像 docker pull mysql這樣是默認拉取最新的版本latest 這樣是指定版本拉取 docker pull mysql:5.7查看已安裝的mysql鏡像 docker images通過鏡像生成容器 docke…

大數據HCIE成神之路之數據預處理(1)——缺失值處理

缺失值處理 1.1 刪除1.1.1 實驗任務1.1.1.1 實驗背景1.1.1.2 實驗目標1.1.1.3 實驗數據解析 1.1.2 實驗思路1.1.3 實驗操作步驟1.1.4 結果驗證 1.2 填充1.2.1 實驗任務1.2.1.1 實驗背景1.2.1.2 實驗目標1.2.1.3 實驗數據解析 1.2.2 實驗思路1.2.3 實驗操作步驟1.2.4 結果驗證 1…

【STM32】ADC模數轉換器

1 ADC簡介 ADC&#xff08;Analog-Digital Converter&#xff09;模擬-數字轉換器 ADC可以將引腳上連續變化的模擬電壓轉換為內存中存儲的數字變量&#xff0c;建立模擬電路到數字電路的橋梁 STM32是數字電路&#xff0c;只有高低電平&#xff0c;沒有幾V電壓的概念&#xff…