【已實測經過】JavaMail經常使用的幾種郵件發送方式

前言

  關於JavaMail發送郵件的代碼,網上隨便搜搜就能夠找到,可是要麼寫得簡單且沒有註釋解釋,要麼寫得複雜又很是雜亂。因爲項目須要,花了一段時間蒐集網上各種案例,熟悉JavaMail郵件發送涉及的配置,取其精華去其糟粕。在功能測試正常可用的前提下,對代碼的排版和註釋進行梳理調整,提煉出符合本身要求的功能代碼,現將它分享給你們,但願你們少走彎路,提升開發效率。代碼測試過程出現的問題,請參看《JavaMail郵件發送成功但未收到郵件的問題及解決辦法》《使用geronimo-javamail_1.4發送郵件的有關說明》分析解決。html

主要類及功能

一、EmailAuthenticator類:繼承Authenticator類的帳號密碼驗證器,主要用於建立郵件會話時調用。
二、EmailSendInfo類:郵件參數信息設置,參數包括帳號、密碼、SMTP服務器地址和服務端口等。
三、EmailSender類:電子郵件發送器,包含各類郵件發送方法,如文本形式、HTML形式和含附件形式等。
注:請到Oracle官網下載JavaMail的jar包,提供如下參考下載地址:java

http://www.oracle.com/technet...
https://java.net/projects/jav...segmentfault

EmailAuthenticator類

import javax.mail.*;   

public class EmailAuthenticator extends Authenticator{   
    
    private String userName;   
    private String password;   
        
    public EmailAuthenticator(){}   
    
    public EmailAuthenticator(String username, String password) {    
        this.userName = username;    
        this.password = password;    
    }    
    
    protected PasswordAuthentication getPasswordAuthentication(){   
        return new PasswordAuthentication(userName, password);   
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }   
    
}

EmailSendInfo類

import java.util.Properties;

public class EmailSendInfo {
    
    // 發送郵件的服務器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    // 郵件發送者的地址
    private String fromAddress;
    // 郵件接收者的地址
    private String toAddress;
    // 登錄郵件發送服務器的用戶名和密碼
    private String userName;
    private String password;
    // 是否須要身份驗證
    private boolean validate = false;
    // 郵件主題
    private String subject;
    // 郵件的文本內容
    private String content;
    // 郵件附件的文件名
    private String[] attachFileNames;

    /**
     * 得到郵件會話屬性
     */
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return mailServerHost;
    }

    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }

    public String getMailServerPort() {
        return mailServerPort;
    }

    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String textContent) {
        this.content = textContent;
    }
}

EmailSender類

  爲了方面你們閱讀,我將EmailSender類的內容進行了拆分,測試使用只須要將下面內容組合就可。其中main方法中的部分參數信息須要自行設置,請勿直接粘貼測試。服務器

import配置

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

用於測試的main方法

public static void main(String[] args) {
    String fromaddr = "XXX@sohu.com";
    String toaddr = "XXX@sohu.com";
//        String title = "【測試標題】Testing Subject-myself-TEXT";
//        String title = "【測試標題】Testing Subject-myself-HTML";
//        String title = "【測試標題】Testing Subject-myself-eml文件";
    String title = "【測試標題】Testing Subject-myself-eml文件_含多個附件";
    String content = "【測試內容】Hello, this is sample for to check send email using JavaMailAPI ";
    String port = "25";
    String host = "smtp.sohu.com";
    String userName = "XXX@sohu.com";
    String password = "XXX";
    
    EmailSendInfo mailInfo = new EmailSendInfo();
     mailInfo.setMailServerHost(host);     
     mailInfo.setMailServerPort(port);    
     mailInfo.setValidate(true); 
     mailInfo.setUserName(userName);    
     mailInfo.setPassword(password);
     mailInfo.setFromAddress(fromaddr);    
     mailInfo.setToAddress(toaddr);    
     mailInfo.setSubject(title);    
     mailInfo.setContent(content);
     mailInfo.setAttachFileNames(new String[]{"file/XXX.jpg","file/XXX.txt"});
      
     //發送文體格式郵件
//         EmailSender.sendTextMail(mailInfo);
     //發送html格式郵件
//         EmailSender.sendHtmlMail(mailInfo);  
     //發送含附件的郵件
     EmailSender.sendAttachmentMail(mailInfo);
     //讀取eml文件發送
//         File emailFile = new File("file/EML_myself-eml.eml");
//         File emailFile = new File("file/EML_reademl-eml文件_含文本附件.eml");
//         File emailFile = new File("file/EML_reademl-eml文件_含圖片附件.eml");
//         File emailFile = new File("file/EML_reademl-eml文件_含多個附件.eml");
//         EmailSender.sendMail(mailInfo, emailFile);
}

以文本格式發送郵件

public static boolean sendTextMail(EmailSendInfo mailInfo) {   
    boolean sendStatus = false;//發送狀態
    // 判斷是否須要身份認證    
    EmailAuthenticator authenticator = null;    
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {    
    // 若是須要身份認證,則建立一個密碼驗證器    
      authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
    }   
    // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
    Session sendMailSession = Session.getInstance(pro, authenticator);    
    //【調試時使用】開啓Session的debug模式
    sendMailSession.setDebug(true);
    try {    
        // 根據session建立一個郵件消息    
        MimeMessage  mailMessage = new MimeMessage(sendMailSession);    
        // 建立郵件發送者地址    
        Address from = new InternetAddress(mailInfo.getFromAddress());    
        // 設置郵件消息的發送者    
        mailMessage.setFrom(from);    
        // 建立郵件的接收者地址,並設置到郵件消息中    
        Address to = new InternetAddress(mailInfo.getToAddress());    
        mailMessage.setRecipient(Message.RecipientType.TO,to);    
        // 設置郵件消息的主題    
        mailMessage.setSubject(mailInfo.getSubject(), "UTF-8");
        // 設置郵件消息發送的時間    
        mailMessage.setSentDate(new Date());    
        // 設置郵件消息的主要內容    
        String mailContent = mailInfo.getContent();    
        mailMessage.setText(mailContent, "UTF-8"); 
//            mailMessage.saveChanges(); 
        
        //生成郵件文件
        createEmailFile("file/EML_myself-TEXT.eml", mailMessage); 
        
        // 發送郵件    
        Transport.send(mailMessage);   
        sendStatus = true;    
    } catch (MessagingException ex) {    
          LOG.error("以文本格式發送郵件出現異常", ex);
          return sendStatus;
    }    
    return sendStatus;    
}

以HTML格式發送郵件

public static boolean sendHtmlMail(EmailSendInfo mailInfo){   
    boolean sendStatus = false;//發送狀態
    // 判斷是否須要身份認證    
    EmailAuthenticator authenticator = null;   
    Properties pro = mailInfo.getProperties();   
    //若是須要身份認證,則建立一個密碼驗證器     
    if (mailInfo.isValidate()) {    
      authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());   
    }    
    // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session    
    Session sendMailSession = Session.getDefaultInstance(pro,authenticator);  
    //【調試時使用】開啓Session的debug模式
    sendMailSession.setDebug(true);
    try {    
        // 根據session建立一個郵件消息    
        Message mailMessage = new MimeMessage(sendMailSession);    
        // 建立郵件發送者地址    
        Address from = new InternetAddress(mailInfo.getFromAddress());    
        // 設置郵件消息的發送者    
        mailMessage.setFrom(from);    
        // 建立郵件的接收者地址,並設置到郵件消息中    
        Address to = new InternetAddress(mailInfo.getToAddress());    
        // Message.RecipientType.TO屬性表示接收者的類型爲TO    
        mailMessage.setRecipient(Message.RecipientType.TO,to);    
        // 設置郵件消息的主題    
        mailMessage.setSubject(mailInfo.getSubject());    
        // 設置郵件消息發送的時間    
        mailMessage.setSentDate(new Date());    
        // 設置郵件內容
        mailMessage.setContent(mailInfo.getContent(), "text/html;charset=utf-8");
        
        //生成郵件文件
        createEmailFile("file/EML_myself-HTML.eml", mailMessage);
        
        // 發送郵件    
        Transport.send(mailMessage);    
        sendStatus = true;    
    } catch (MessagingException ex) {    
        LOG.error("以HTML格式發送郵件出現異常", ex);    
        return sendStatus;
    }    
    return sendStatus;    
}

讀取eml文件後發送郵件

public static boolean sendMail(EmailSendInfo mailInfo, File emailFile) {
    boolean sendStatus = false;//發送狀態
    // 判斷是否須要身份認證    
    EmailAuthenticator authenticator = null;    
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {    
    // 若是須要身份認證,則建立一個密碼驗證器    
      authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
    }   
    // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
    Session sendMailSession = Session.getInstance(pro, authenticator);    
    //【調試時使用】開啓Session的debug模式
    sendMailSession.setDebug(true);
    try {    
        InputStream source = new FileInputStream(emailFile);
        // 根據session建立一個郵件消息    
         Message  mailMessage = new MimeMessage(sendMailSession, source);    
        // 發送郵件    
        Transport.send(mailMessage);   
        //【重要】關閉輸入流,不然會致使文件沒法移動或刪除
        source.close();
        sendStatus = true;    
    } catch (MessagingException e) {    
          LOG.error("以文本格式發送郵件出現異常", e);
          return sendStatus;
    } catch (FileNotFoundException e) {
        LOG.error("FileNotFoundException", e);
        return sendStatus;   
    } catch (Exception e) {
        LOG.error("Exception", e);
        return sendStatus;
    }
    return sendStatus;    
}

以含附件形式發送郵件

public static boolean sendAttachmentMail(EmailSendInfo mailInfo) {
    boolean sendStatus = false;//發送狀態
    // 判斷是否須要身份認證    
    EmailAuthenticator authenticator = null;    
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {    
    // 若是須要身份認證,則建立一個密碼驗證器    
      authenticator = new EmailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
    }   
    // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
    Session sendMailSession = Session.getInstance(pro, authenticator);    
    //【調試時使用】開啓Session的debug模式
    sendMailSession.setDebug(true);
    try {    
        // 根據session建立一個郵件消息    
        MimeMessage  mailMessage = new MimeMessage(sendMailSession);    
        // 建立郵件發送者地址    
        Address from = new InternetAddress(mailInfo.getFromAddress());    
        // 設置郵件消息的發送者    
        mailMessage.setFrom(from);    
        // 建立郵件的接收者地址,並設置到郵件消息中    
        Address to = new InternetAddress(mailInfo.getToAddress());    
        mailMessage.setRecipient(Message.RecipientType.TO,to);    
        // 設置郵件消息的主題    
        mailMessage.setSubject(mailInfo.getSubject(), "UTF-8");
        // 設置郵件消息發送的時間    
        mailMessage.setSentDate(new Date());    
        // 設置郵件消息的主要內容    
        String mailContent = mailInfo.getContent();   
        // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象    
        Multipart mainPart = new MimeMultipart();    
        // 建立一個包含HTML內容的MimeBodyPart    
        BodyPart bodyPart = new MimeBodyPart();    
        //設置TEXT內容
//            bodyPart.setText(mailInfo.getContent());
        // 設置HTML內容    
        bodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");    
        mainPart.addBodyPart(bodyPart);    
        //設置附件
         String[] filenames = mailInfo.getAttachFileNames();
         for (int i = 0; i < filenames.length; i++) {
             // Part two is attachment  
             bodyPart = new MimeBodyPart();  
             String filename = filenames[i];//1.txt/sohu_mail.jpg
//                 DataSource source = new FileDataSource(filename);  
             FileDataSource source = new FileDataSource(filename); 
             bodyPart.setDataHandler(new DataHandler(source));  
             bodyPart.setFileName(source.getName());  
             mainPart.addBodyPart(bodyPart);  
        }
        // 將MiniMultipart對象設置爲郵件內容    
        mailMessage.setContent(mainPart); 
        
        //生成郵件文件
        createEmailFile("file/EML_reademl-eml文件_含多個附件.eml", mailMessage); 
        
        // 發送郵件    
        Transport.send(mailMessage);   
        sendStatus = true;    
    } catch (MessagingException ex) {    
          LOG.error("以文本格式發送郵件出現異常", ex);
          return sendStatus;
    }    
    return sendStatus;    
}

生成郵件文件

public static void createEmailFile(String fileName, Message mailMessage)
        throws MessagingException {
    
    File f = new File(fileName); 
    try {
        mailMessage.writeTo(new FileOutputStream(f));
    } catch (IOException e) {
        LOG.error("IOException", e);  
    }
}
相關文章
相關標籤/搜索