java郵件發送工具

来源:https://www.cnblogs.com/a526583280/archive/2019/05/01/10800415.html
-Advertisement-
Play Games

最近在web項目中,客戶端註冊時需要通過郵箱驗證,伺服器就需要向客戶端發送郵件,我把發送郵件的細節進行了簡易的封裝: 最近在web項目中,客戶端註冊時需要通過郵箱驗證,伺服器就需要向客戶端發送郵件,我把發送郵件的細節進行了簡易的封裝: 在maven中需要導入: 1 <!--Email--> 2 <d ...


最近在web項目中,客戶端註冊時需要通過郵箱驗證,伺服器就需要向客戶端發送郵件,我把發送郵件的細節進行了簡易的封裝:

在maven中需要導入:

 1 <!--Email-->
 2 <dependency>
 3    <groupId>javax.mail</groupId>
 4    <artifactId>mail</artifactId>
 5    <version>1.4.7</version>
 6 </dependency>
 7 <dependency>
 8    <groupId>javax.activation</groupId>
 9    <artifactId>activation</artifactId>
10    <version>1.1.1</version>
11 </dependency>

 

發送方的封裝:

 1 import javax.mail.Authenticator;
 2 import javax.mail.PasswordAuthentication;
 3 import javax.mail.Session;
 4 import java.util.Properties;
 5 
 6 public abstract class MailSession implements EmailConstant {
 7     // Mail的Session對象
 8     protected Session session;
 9     // 發送方郵箱
10     protected String srcEmail;
11     // 發送方的授權碼(不是郵箱登陸密碼,如何獲取請百度)
12     protected String authCode;
13 
14     protected MailSession(String srcEmail, String authCode) {
15         this.srcEmail = srcEmail;
16         this.authCode = authCode;
17 
18         createSession();
19     }
20 
21     protected abstract void doCreateSession(Properties properties);
22 
23     private void createSession() {
24         // 獲取系統屬性,並設置
25         Properties properties = System.getProperties();
26         // 由於不同的郵箱在初始化Session時有不同的操作,需要由子類實現
27         doCreateSession(properties);
28         properties.setProperty(MAIL_AUTH, "true");
29         
30         // 生成Session對象
31         session = Session.getDefaultInstance(properties, new Authenticator() {
32             @Override
33             public PasswordAuthentication getPasswordAuthentication() {
34                 return new PasswordAuthentication(srcEmail, authCode);
35             }
36         });
37     }
38 
39     public Session getSession() {
40         return session;
41     }
42 
43     public String getSrcEmail() {
44         return srcEmail;
45     }
46 
47     @Override
48     public String toString() {
49         return "MailSession{" +
50                 "session=" + session +
51                 ", srcEmail='" + srcEmail + '\'' +
52                 ", authCode='" + authCode + '\'' +
53                 '}';
54     }
55 
56 }

EmailConstant :

 1 /**
 2 *  需要的系統屬性
 3 **/
 4 public interface EmailConstant {
 5     String HOST_QQ = "smtp.qq.com";
 6     String HOST_163 = "smtp.163.com";
 7     String MAIL_HOST = "mail.smtp.host";
 8     String MAIL_AUTH = "mail.smtp.auth";
 9     String MAIL_SSL_ENABLE = "mail.smtp.ssl.enable";
10     String MAIL_SSL_SOCKET_FACTORY = "mail.smtp.ssl.socketFactory";
11 }

163郵箱的系統設置:

 1 public class WYMailSession extends MailSession {
 2 
 3     public WYMailSession(String srcEmail, String authCode) {
 4         super(srcEmail, authCode);
 5     }
 6 
 7     @Override
 8     protected void doCreateSession(Properties properties) {
 9         properties.setProperty(MAIL_HOST, EmailConstant.HOST_163);
10     }
11 
12 }

QQ郵箱的系統設置:

 1 public class QQMailSession extends MailSession {
 2 
 3     public QQMailSession(String srcEmail, String authCode) {
 4         super(srcEmail, authCode);
 5     }
 6 
 7     @Override
 8     protected void doCreateSession(Properties properties) {
 9         properties.setProperty(MAIL_HOST, EmailConstant.HOST_QQ);
10 
11         try {
12             MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
13             mailSSLSocketFactory.setTrustAllHosts(true);
14             properties.put(MAIL_SSL_ENABLE, "true");
15             properties.put(MAIL_SSL_SOCKET_FACTORY, mailSSLSocketFactory);
16         } catch (GeneralSecurityException e) {
17             e.printStackTrace();
18         }
19     }
20 
21 }

發送的郵件封裝:

 1 public class MailMessage {
 2     // 接收方郵箱
 3     private String tagEmail;
 4     // 主題
 5     private String subJect;
 6     // 內容
 7     private String content;
 8 
 9     public MailMessage(String tagEmail, String subJect, String content) {
10         this.tagEmail = tagEmail;
11         this.subJect = subJect;
12         this.content = content;
13     }
14 
15     public String getTagEmail() {
16         return tagEmail;
17     }
18 
19     public String getSubJect() {
20         return subJect;
21     }
22 
23     public String getContent() {
24         return content;
25     }
26 
27     @Override
28     public String toString() {
29         return "MailMessage{" +
30                 "tagEmail='" + tagEmail + '\'' +
31                 ", subJect='" + subJect + '\'' +
32                 ", content='" + content + '\'' +
33                 '}';
34     }
35 
36 }

發送部分:

  1 import com.zc.util.logger.Logger;
  2 import com.zc.util.logger.LoggerFactory;
  3 
  4 import javax.mail.Message;
  5 import javax.mail.MessagingException;
  6 import javax.mail.Transport;
  7 import javax.mail.internet.InternetAddress;
  8 import javax.mail.internet.MimeMessage;
  9 import java.util.Queue;
 10 import java.util.concurrent.ConcurrentLinkedQueue;
 11 import java.util.concurrent.Executor;
 12 
 13 public class MailSender {
 14 
 15     private static final Logger LOGGER = LoggerFactory.getLogger(MailSender.class);
 16   // 這個隊列是有在多個發送方的情況下,可以輪流發送
 17     private final Queue<MailSession> queue = new ConcurrentLinkedQueue<>();
 18   // 使用線程池,讓線程去完成發送
 19     private final Executor executor;
 20 
 21     public MailSender(Executor executor) {
 22         this.executor = executor;
 23     }
 24   // 指定發送方,發送郵件
 25     public void sendTo(MailSession mailSession, MailMessage mailMessage) {
 26         if (mailSession == null) {
 27             String msg = "MailSender sendTo(), mailSession can not null!";
 28             if (LOGGER.isErrorEnabled()) {
 29                 LOGGER.error(msg);
 30             }
 31             throw new NullPointerException(msg);
 32         }
 33 
 34         if (!queue.contains(mailSession)) {
 35             addSender(mailSession);
 36         }
 37 
 38         executor.execute(new Runnable() {
 39             @Override
 40             public void run() {
 41                 Message message = new MimeMessage(mailSession.getSession());
 42                 try {
 43                     message.setFrom(new InternetAddress(mailSession.getSrcEmail()));
 44                     // 設置接收人
 45                     message.addRecipient(Message.RecipientType.TO,
 46                             new InternetAddress(mailMessage.getTagEmail()));
 47                     // 設置郵件主題
 48                     message.setSubject(mailMessage.getSubJect());
 49                     // 設置郵件內容
 50                     message.setContent(mailMessage.getContent(), "text/html;charset=UTF-8");
 51                     // 發送郵件
 52                     Transport.send(message);
 53 
 54                     if (LOGGER.isInfoEnabled()) {
 55                         LOGGER.info("MailSender [thread:" + Thread.currentThread().getName()
 56                                 + "] send email["
 57                                 + "from: " + mailSession.getSrcEmail()
 58                                 + ", to: " + mailMessage.getTagEmail()
 59                                 + ", subject: " + mailMessage.getSubJect()
 60                                 + ", content: " + mailMessage.getContent()
 61                                 + "]");
 62                     }
 63                 } catch (MessagingException e) {
 64                     e.printStackTrace();
 65                 }
 66 
 67             }
 68         });
 69     }
 70   // 未指定發送方,由隊列輪流發送
 71     public void sendTo(MailMessage mailMessage) {
 72         if (mailMessage == null) {
 73             String msg = "MailSender sendTo(), mailMessage not defined!";
 74             if (LOGGER.isErrorEnabled()) {
 75                 LOGGER.error(msg);
 76             }
 77             throw new NullPointerException(msg);
 78         }
 79 
 80         MailSession mailSession = queue.poll();
 81         queue.add(mailSession);
 82 
 83         sendTo(mailSession, mailMessage);
 84     }
 85 
 86     public void addSender(MailSession mailSession) {
 87         if (mailSession == null) {
 88             String msg = "MailSender addSender(), sender not defined!";
 89             if (LOGGER.isErrorEnabled()) {
 90                 LOGGER.error(msg);
 91             }
 92             throw new NullPointerException(msg);
 93         }
 94 
 95         queue.add(mailSession);
 96 
 97         if (LOGGER.isInfoEnabled()) {
 98             LOGGER.info("MailSender add sender:[" + mailSession + "]");
 99         }
100     }
101 
102     public MailSession removeSender(MailSession mailSession) {
103         if (queue.remove(mailSession)) {
104             if (LOGGER.isInfoEnabled()) {
105                 LOGGER.info("MailSender remove sender:[" + mailSession + "]");
106             }
107         }
108 
109         return mailSession;
110     }
111 
112 }

 

測試:

 1 public class Demo {
 2 
 3     public static void main(String[] args) {
 4         Executor executor = Executors.newCachedThreadPool(new NamedThreadFactory("ZC_Email"));
 5         MailSender sender = new MailSender(executor);
 6         sender.sendTo(new QQMailSession("[email protected]", "xxxxx"),
 7                 new MailMessage("[email protected]", "java郵件!", "這是使用java發送的郵件!請查收"));
 8         
 9         // TODO 記得線程池的關閉
10     }
11 
12 }

日誌輸出:

1 18:24:02.871 [main] INFO com.zc.util.logger.LoggerFactory - using logger: com.zc.util.logger.slf4j.Slf4jLoggerAdapter
2 18:24:04.243 [main] INFO com.zc.util.mail.MailSender -  [ZC-LOGGER] MailSender add sender:[MailSession{session=javax.mail.Session@1134affc, srcEmail='[email protected]', authCode='ijsuavtbasohbgbb'}], current host: 172.19.126.174
3 18:24:05.990 [ZC_Email-thread-1] INFO com.zc.util.mail.MailSender -  [ZC-LOGGER] MailUtils [thread:ZC_Email-thread-1] send email[from: [email protected], to: [email protected], subject: java郵件!, content: 這是使用java發送的郵件!請查收], current host: 172.19.126.174

郵件截圖:


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一:什麼是Spring框架? spring是一個分層的javase/EEfull-stack(一站式)輕量級的java開源框架。是為瞭解決企業開發的複雜性而創建的。框架的主要優勢是分層架構,Spring的核心是控制反轉(IOC)和麵向切麵(AOP)。 二.學習Spring的好處? 主要就是方便解耦, ...
  • 一:基礎語法之--標識符,修飾符,關鍵字 1.標識符: 定義:類名、變數名以及方法名都被稱為標識符。 註意: ·所有的標識符都應該以字母(A-Z或者a-z),美元符($)、或者下劃線(_)開始·首字元之後可以是字母(A-Z或者a-z),美元符($)、下劃線(_)或數字的任何字元組合·關鍵字不能用作標 ...
  • Python基礎之參數與返回值進階,包括 函數的返回值 進階,函數的參數進階,函數的遞歸。其中,函數的返回值 進階 包括 利用元組返回多個函數值,用多個變數接收函數的返回值;函數的參數進階 包括 函數內部變數和參數的關係,列表調用+=,預設參數,多值參數,元組和字典的拆包;函數的遞歸 僅包括 函數的... ...
  • 概述 這是關於 Swoole 學習的第三篇文章:Swoole WebSocket 的應用。 "第二篇:Swoole Task 的應用" "第一篇:Swoole Timer 的應用" 什麼是 WebSocket ? WebSocket 是一種在單個TCP連接上進行全雙工通信的協議。 WebSocket ...
  • 工作一年,維護工程項目的同時一直寫CURD,最近學習DDD,結合之前自己寫的開源項目,深思我們這種CURD的編程方式的弊端,和朋友討論後,發現我們從來沒有面向對象開發,所以寫這篇文章,希望更多人去思考面向對象,不只是停留在背書上 下麵以開發一個常規的登錄模塊為例,模擬實現一個登錄功能,一步步地去說明 ...
  • 5.1自學自我總結 1.關於數據類型補充 在整列中除了int數據類型,還要long數據數據類型 ling為長數字 另外還有一種未被提到的數據類型為虛數complex在python中虛數為5j來表示 個個數字函數的也可以相互裝換 如下 2.關於字元串 字元串取值 3.不同類型變數拼接新增方法 五一快樂 ...
  • 關於Java 鎖的知識整理與回顧(個人筆記): 鎖有哪些,分別用來幹嘛? Java實現鎖有兩種方式,synchronized關鍵字和Lock (1)Lock(可判斷鎖狀態) Lock是基於JDK層面實現。Lock的實現主要有ReentrantLock、ReadLock和WriteLock(引出鎖分類 ...
  • 利用map和reduce編寫一個str2float函數,把字元串'123.456'轉換成浮點數123.456。 思路:計算小數位數 >將字元串中的小數點去掉 >字元串轉換為整數 >整數轉換為浮點數 知識點: 1、將字元串中的小數點去掉可以用切片的方法。 2、reduce把一個函數作用在一個序列[x1 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...