1. 程式人生 > >通過javaMail傳送郵件,可選新增多個收件人,密送,抄送,多個附件,超實用

通過javaMail傳送郵件,可選新增多個收件人,密送,抄送,多個附件,超實用

        自己通過學習多人的程式碼,並整理了一個簡單,呼叫方便的通過javaMail傳送郵件。只需填寫發件郵箱地址,密碼;收件人地址,附件,選擇是否儲存,設定自己傳送郵件時的暱稱就ok了。程式碼自動匹配設定smtp服務地址和埠。

    傳送郵件需要郵箱地址和密碼,開啟POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務。各大郵箱使用外部登入驗證的方式不一樣,有些需要使用授權碼登入連結,有些只需要郵箱登入密碼,這個得根據你使用的郵箱服務平臺的規定了。這裡我收集了下面的郵箱smtp服務地址和埠,【QQ、Foxmail、139、126、163、Google(gmail)、Exchange、Outlook、sina.cn、sina.com

】這些足以夠用了吧!不多說,看程式碼。

    使用方法

 public static void main(String[] args) throws Exception {

        List<String> map = new ArrayList<>();
        map.add("[email protected]");
        map.add("[email protected]");
        map.add("[email protected]");
        new SendEmail("[email protected]
", "密碼") .setDebug(true) .setMyNickName("這是我的暱稱") .addFile("C:/Users/25171/Pictures/timg.jpg")//新增附件 .addFile("C:/Users/25171/Desktop/QQ圖片20180317192741.jpg") // .addFile(List<String> list)//新增附件集合 .setSaveEmail("C:/User/2517/Desktop/name.eml")//儲存郵件 .addRecipientT0("
[email protected]
")//新增收件人地址 // .addRecipientT0(map)//新增收件人地址集合 // .addRecipientCC(map)//新增密送收件人地址 // .addRecipientBCC(map)//新增抄送收件人地址 .createMail("標題", "傳送的內容", "text/html;charset=utf-8") .sendEmail(new SendEmail.Callback() { @Override public void success(String s) { System.out.println(s);//傳送完成後回撥介面 } @Override public void error(String s, Exception e) { System.out.println(s); e.printStackTrace();//異常失敗的回撥介面 } }); }

主體工具程式碼

package com.sai.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class SendEmail {

    public interface Callback {
        void success(String s);

        void error(String s, Exception e);
    }

    private Callback callback;  //資訊回撥介面
    private Properties properties;//系統屬性物件
    private String mailAccount;   //傳送郵箱地址
    private String mailPassword;  //驗證密碼
    private Session session;      //郵件會話物件
    private String myNickName;    //暱稱,傳送時自己的暱稱
    private boolean debug = false;//debug模式
    private boolean isSaveEmail = false;
    private String pathName = "exc.eml";//郵件儲存時的

    public SendEmail(String mailAccount, String mailPassword) {
        this.mailAccount = mailAccount;
        this.mailPassword = mailPassword;
    }

    public SendEmail setSaveEmail(String pathName) {
        isSaveEmail = true;
        this.pathName = pathName;
        return this;
    }

    private List<String> recipientT0List = new ArrayList<>();//收件地址
    private List<String> recipientCCList = new ArrayList<>();//密送地址
    private List<String> recipientBCCList = new ArrayList<>();//抄送地址
    private List<String> filePath = new ArrayList<>();//附件

    public SendEmail setDebug(boolean sessionDebug) {
        debug = sessionDebug;
        return this;
    }

    /*** 設定多人收件人地址 */
    public SendEmail addRecipientT0(String address) {
        recipientT0List.add(address);
        return this;
    }

    public SendEmail addRecipientCC(String address) {
        recipientCCList.add(address);
        return this;
    }

    public SendEmail addRecipientBCC(String address) {
        recipientBCCList.add(address);
        return this;
    }

    public SendEmail addRecipientT0(List<String> address) {
        recipientT0List.addAll(address);
        return this;
    }

    public SendEmail addRecipientCC(List<String> address) {
        recipientCCList.addAll(address);
        return this;
    }

    public SendEmail addRecipientBCC(List<String> address) {
        recipientBCCList.addAll(address);
        return this;
    }

    /***新增檔案***/
    public SendEmail addFile(String filePath) {
        this.filePath.add(filePath);
        return this;
    }

    public SendEmail addFile(List<String> list) {
        this.filePath.addAll(list);
        return this;
    }

    /****暱稱設定**/
    public SendEmail setMyNickName(String name) {
        myNickName = name;
        return this;
    }

    private MimeMessage message;

    /**
     * @param title 主題
     * @param datas 內容
     * @param type  內容格式型別 text/html;charset=utf-8
     * @return s
     */
    public SendEmail createMail(String title, String datas, String type) {
        if (mailAccount.length() == 0 || mailAccount.equals(null)) {
            System.err.println("發件地址不存在!");
            return this;
        }
        if (myNickName == null) {
            myNickName = mailAccount;
        }
        getProperties();
        if (!sync) return this;
        try {
            message = new MimeMessage(session);
            // 設定傳送郵件地址,param1 代表傳送地址 param2 代表傳送的名稱(任意的) param3 代表名稱編碼方式
            message.setFrom(new InternetAddress(mailAccount, myNickName, "utf-8"));

            setRecipientT0();   //新增接收人地址
            setRecipientCC();   //新增抄送接收人地址
            setRecipientBCC();  //新增密送接收人地址
            BodyPart messageBodyPart = new MimeBodyPart();  // 建立訊息部分
            Multipart multipart = new MimeMultipart();      // 建立多重訊息

            messageBodyPart.setContent(datas, type);        // 訊息內容
            multipart.addBodyPart(messageBodyPart);         // 設定文字訊息部分

            addFile(multipart);                             //附件部分
            // 傳送完整訊息
            message.setContent(multipart);
            message.setSubject(title);              // 設定郵件主題
            message.setSentDate(new Date());        // 設定傳送時間
            message.saveChanges();                  // 儲存上面的編輯內容
            // 將上面建立的物件寫入本地
            saveEmail(title);
        } catch (Exception e) {
            if (callback != null)
                callback.error("message error ", e);
            sync = false;
        }
        return this;
    }

    public void sendEmail(Callback callback) {
        this.callback = callback;
        if (!sync)
            return;
        try {
            Transport trans = session.getTransport();
            // 連結郵件伺服器
            trans.connect(mailAccount, mailPassword);
            // 傳送資訊
            trans.sendMessage(message, message.getAllRecipients());
            // 關閉連結
            trans.close();
            if (callback != null)
                callback.success("傳送完成");
        } catch (Exception e) {
            if (callback != null)
                callback.error("傳送異常", e);
        }
    }

    private void saveEmail(String title) throws IOException, MessagingException {
        OutputStream out = null;
        if (isSaveEmail) {
            if (pathName.length() == 0 || pathName.equals(null)) {
                out = new FileOutputStream(title + ".eml");
            } else {
                String path[] = pathName.split("\\.");
                out = new FileOutputStream(path[0] + title + ".eml");
            }
        }
        message.writeTo(out);
        out.flush();
        out.close();
    }

    /*** 設定收件人地址資訊*/
    private void setRecipientT0() throws MessagingException, UnsupportedEncodingException {
        if (recipientT0List.size() > 0) {
            InternetAddress[] sendTo = new InternetAddress[recipientT0List.size()];
            for (int i = 0; i < recipientT0List.size(); i++) {
                System.out.println("傳送到:" + recipientT0List.get(i));
                sendTo[i] = new InternetAddress(recipientT0List.get(i), "", "UTF-8");
            }
            message.addRecipients(MimeMessage.RecipientType.TO, sendTo);
        }
    }

    /***設定密送地址**/
    private void setRecipientCC() throws MessagingException, UnsupportedEncodingException {
        if (recipientCCList.size() > 0) {
            InternetAddress[] sendTo = new InternetAddress[recipientCCList.size()];
            for (int i = 0; i < recipientCCList.size(); i++) {
                System.out.println("傳送到:" + recipientCCList.get(i));
                sendTo[i] = new InternetAddress(recipientCCList.get(i), "", "UTF-8");
            }
            message.addRecipients(MimeMessage.RecipientType.CC, sendTo);
        }
    }

    /***設定抄送郵件地址**/
    private void setRecipientBCC() throws MessagingException, UnsupportedEncodingException {
        if (recipientBCCList.size() > 0) {
            InternetAddress[] sendTo = new InternetAddress[recipientBCCList.size()];
            for (int i = 0; i < recipientBCCList.size(); i++) {
                System.out.println("傳送到:" + recipientBCCList.get(i));
                sendTo[i] = new InternetAddress(recipientBCCList.get(i), "", "UTF-8");
            }
            message.addRecipients(MimeMessage.RecipientType.BCC, sendTo);
        }
    }

    /***新增附件****/
    private void addFile(Multipart multipart) throws MessagingException, UnsupportedEncodingException {
        if (filePath.size() == 0)
            return;
        for (int i = 0; i < filePath.size(); i++) {
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // 選擇出每一個附件名
            String pathName = filePath.get(i);
            System.out.println("新增附件 ====>" + pathName);
            // 得到資料來源
            FileDataSource fds = new FileDataSource(pathName);
            // 得到附件本身並至入BodyPart
            messageBodyPart.setDataHandler(new DataHandler(fds));
            //採用這去除中文亂碼
            messageBodyPart.setFileName(MimeUtility.encodeText(fds.getName()));
            multipart.addBodyPart(messageBodyPart);
        }
    }

    private boolean sync = true;

    /**
     * 規定設定 傳輸協議為smtp  根據輸入的郵箱地址自動匹配smtp伺服器地址與smtp伺服器地址埠
     */
    private void getProperties() {
        String account[] = mailAccount.split("@");
        String mailTpye = "";
        try {
            mailTpye = account[1];
        } catch (Exception e) {
            System.err.println("不正確的郵箱地址!");
            sync = false;
            return;
        }
        String SMTPHost = "";//smtp伺服器地址
        String SMTPPort = "";//smtp伺服器地址埠
        switch (mailTpye) {
            case "qq.com":
            case "foxmail.com":
                SMTPHost = "smtp.qq.com";
                SMTPPort = "465";
                break;
            case "sina.com":
                SMTPHost = "smtp.sina.com";
                SMTPPort = "25";
                break;
            case "sina.cn":
                SMTPHost = "smtp.sina.cn";
                SMTPPort = "25";
                break;
            case "139.com":
                SMTPHost = "smtp.139.com";
                SMTPPort = "465";
                break;
            case "163.com":
                SMTPHost = "smtp.163.com";
                SMTPPort = "25";
                break;
            case "188.com":
                SMTPHost = "smtp.188.com";
                SMTPPort = "25";
                break;
            case "126.com":
                SMTPHost = "smtp.126.com";
                SMTPPort = "25";
                break;
            case "gmail.com":
                SMTPHost = "smtp.gmail.com";
                SMTPPort = "465";
                break;
            case "outlook.com":
                SMTPHost = "smtp.outlook.com";
                SMTPPort = "465";
                break;
            default:
                System.err.println("暫時不支援此賬號作為服務賬號傳送郵件!");
                return;
        }
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", "smtp"); // 設定郵件傳輸採用的協議smtp
        prop.setProperty("mail.smtp.host", SMTPHost);// 設定傳送人郵件伺服器的smtp地址
        prop.setProperty("mail.smtp.auth", "true");     // 設定驗證機制
        prop.setProperty("mail.smtp.port", SMTPPort);// SMTP 伺服器的埠 (非 SSL 連線的埠一般預設為 25, 可以不新增, 如果開啟了 SSL 連線,
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", SMTPPort);
        properties = prop;
        session = Session.getInstance(properties);
        session.setDebug(debug);
    }

}

        完成這些需要匯入的重要jar包:mail-1.4.1.jar(或者更高的版本) 和 activation 包,jdk1.8中rt.jar包含的activation 包。所以jdk1.8的就無需考慮activation 怎麼下載了。

        完成解析分配伺服器地址和埠的主要函式(寫的不怎麼好):

 private void getProperties() {
        String account[] = mailAccount.split("@");
        String mailTpye = "";
        try {
            mailTpye = account[1];
        } catch (Exception e) {
            System.err.println("不正確的郵箱地址!");
            sync = false;
            return;
        }
        String SMTPHost = "";//smtp伺服器地址
        String SMTPPort = "";//smtp伺服器地址埠
        switch (mailTpye) {
            case "qq.com":
            case "foxmail.com":
                SMTPHost = "smtp.qq.com";
                SMTPPort = "465";
                break;
            case "sina.com":
                SMTPHost = "smtp.sina.com";
                SMTPPort = "25";
                break;
            case "sina.cn":
                SMTPHost = "smtp.sina.cn";
                SMTPPort = "25";
                break;
            case "139.com":
                SMTPHost = "smtp.139.com";
                SMTPPort = "465";
                break;
            case "163.com":
                SMTPHost = "smtp.163.com";
                SMTPPort = "25";
                break;
            case "188.com":
                SMTPHost = "smtp.188.com";
                SMTPPort = "25";
                break;
            case "126.com":
                SMTPHost = "smtp.126.com";
                SMTPPort = "25";
                break;
            case "gmail.com":
                SMTPHost = "smtp.gmail.com";
                SMTPPort = "465";
                break;
            case "outlook.com":
                SMTPHost = "smtp.outlook.com";
                SMTPPort = "465";
                break;
            default:
                System.err.println("暫時不支援此賬號作為服務賬號傳送郵件!");
                return ;
        }
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", "smtp"); // 設定郵件傳輸採用的協議smtp
        prop.setProperty("mail.smtp.host", SMTPHost);// 設定傳送人郵件伺服器的smtp地址
        prop.setProperty("mail.smtp.auth", "true");     // 設定驗證機制
        prop.setProperty("mail.smtp.port", SMTPPort);// SMTP 伺服器的埠 (非 SSL 連線的埠一般預設為 25, 可以不新增
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", SMTPPort);
        properties = prop;
        session = Session.getInstance(properties);
        session.setDebug(debug);
    }

最後看看效果:


相關推薦

通過javaMail傳送郵件增多收件人抄送附件,實用

        自己通過學習多人的程式碼,並整理了一個簡單,呼叫方便的通過javaMail傳送郵件。只需填寫發件郵箱地址,密碼;收件人地址,附件,選擇是否儲存,設定自己傳送郵件時的暱稱就ok了。程式碼自動匹配設定smtp服務地址和埠。    傳送郵件需要郵箱地址和密碼,開啟P

uni-app 是一個使用 Vue.js 開發跨平臺應用的前端框架開發者編寫一套程式碼編譯到iOS、Android、微信小程式等平臺。

uni-app 是一個使用 Vue.js 開發跨平臺應用的前端框架,開發者編寫一套程式碼,可編譯到iOS、Android、微信小程式等多個平臺。 uni-app在跨端數量、擴充套件能力、效能體

越過GFW使用JavaMail通過Gmail傳送郵件

程式碼參考了:https://blog.csdn.net/licl19870605/article/details/8164401 Gmail要做兩處的設定: 1)啟用IMAP(如果只使用smtp協議傳送郵件,強烈懷疑此步可選) 根據 https://support.google.co

Java(SpringCloud) 使用Thymeleaf渲染模板通過Mailgun傳送郵件

好久沒發部落格了,忙東忙西的,堅持! 本文介紹Java使用Mailgun搭建傳送郵件的服務。 我把這個郵件服務放在了我的springCloudApplication(微服務Demo)專案的utilservice服務模組中。 原始碼地址:springCloudA

spring boot 用javaMail傳送郵件很多坑

直接傳送總是報錯 554 dt:spm 被163攔截,認為非法,抄送一份給自己就解決了。但是顯示抄送人,很煩。 service層 package com.llong.email.mail; import org.springframework.beans.factory.anno

javaMail傳送郵件標題/發件人/附件名稱亂碼

javaMail傳送郵件subject會亂碼。 解決辦法: 方法一 在設定主題message.setSubject("なにがありましたら、伝えてくださいね"); 之前設定System.setProperty("mail.mime.charset","UTF-8"); 方法

java傳送郵件javaMail通過SMTP傳送郵件

java傳送郵件一般使用在註冊賬號時、或其他通知資訊時,網站會使用郵件定時傳送、或觸發傳送郵件通知使用者; 1、我是用的是maven開發,所以需要在pom檔案中定義jar包: <dependency> <groupId>javax.

JavaMail傳送郵件後再通過JavaMail接收格式問題

複雜郵件傳送問題 關於 JavaMail 如何傳送郵件這裡就不贅述了,網上有很多例子。其中最複雜的郵件傳送莫過於 html郵件包含內嵌圖片以及附件,最近專案中的這項功能我在傳送郵件時就出現了一系列問題。 我在使用 JavaMail 傳送了郵件之後,會再次通過 JavaMail 將其

函數與字典參數和while語句結合的簡單應用

函數python函數可以與各種語句相結合,以達到提高效率簡化流程的目的: 通過函數創建字典eg. 將歌手與專輯對應,並儲存在字典當中 def make_ablum(name, album): """返回整潔的字典格式""" album_details = {‘singer‘: name,

一鍵掛載磁盤掛載目錄版

一鍵掛載磁盤可選掛載目錄版BT-Panel Linux自動磁盤掛載工具1.4(2017/010/19更新)372065 最近發現很多用戶反饋的一些問題與磁盤掛載有關,1、安裝完面板後發現磁盤容量與實際購買容量不符2、重啟服務器後面板無法訪問,網站、數據庫文件丟失以上都是因為未掛載磁盤,或掛載操作不當引起的,為

telnet通過smtp傳送郵件

////////////////////////////////////CMD指令////////////////////////////////////////////// cmd telnet smtp.163.com 25   or &nb

通過javamailsenderimpl傳送郵件

參考文章:http://blog.csdn.net/qq_33556185/article/details/51028952 import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.anno

JavaMail傳送郵件時出現MailSSLSocketFactory異常問題

昨天晚上在調畢業設計程式的時候,系統中有一個傳送郵件的功能,但是在點擊發送後,程式報了錯,異常資訊是 java.lang.ClassNotFoundException: com.sun.mail.util.MailSSLSocketFactory,然後第一反應是jar包中沒有這個類,然後在ma

Spring JavaMail傳送郵件

JavaMail的介紹      JavaMail,顧名思義,提供給開發者處理電子郵件相關的程式設計介面。它是Sun釋出的用來處理email的API。它可以方便地執行一些常用的郵件傳輸。    雖然JavaMail是Sun的A

Spring(非boot)通過ssl傳送郵件

參考:https://blog.csdn.net/liguo9860/article/details/6874040   我這裡就說一下使用Spring的JavaMailSender如何實現 1. 配置JavaMailSender @Bean public JavaM

js通過外掛傳送郵件

這個外掛為SmtpJS 官網地址為  https://www.smtpjs.com/ 方法很簡單 <script src="https://smtpjs.com/v2/smtp.js"> </script> Email.send( "[email&#

SpringBoot整合JavaMail傳送郵件 --轉載

JavaMail是SUN提供給廣大Java開發人員的一款郵件傳送和接受的一款開源類庫,支援常用的郵件協議,如:SMTP、POP3、IMAP,開發人員使用JavaMail編寫郵件程式時,不再需要考慮底層的通訊細節如:Socket而是關注在邏輯層面。JavaMail可以傳送各種複雜MIME格式的郵件內容

Zabbix 配置通過sendEmail傳送郵件報警

## 1、安裝sendEmail### 1.1、下載安裝sendEmail1. 通過Linux下載命令`wget http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz`(wget安裝命令:`rpm install w

java使用javamail傳送郵件

1.pom.xml檔案配置 <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.

自定義的log列印函式(C++版本列印優先順序及輸出到檔案)

log列印函式,功能如講解如下: 1 可控制巨集COUT_LEVEL決定log,輸出等級,預設為3,輸出ULOGE,ULOGW,ULOGI 2 可控制巨集FS_IN是否輸出到檔案,可通過巨集FILE_LEVEL決定輸出等級,預設為3,檔案路徑為當前路徑,名字預設為outp