javamail參考

ZHOU_VIP發表於2018-09-01
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);
    }
 
}