1. 程式人生 > >JavaMail實現帶附件的收發郵件

JavaMail實現帶附件的收發郵件

sage use multi 客戶端設置 多個 javax 發送 pro 自己

一、前言

參考博客: 

http://blog.csdn.net/xietansheng/article/details/51722660

http://www.cnblogs.com/HigginCui/p/5764509.html

關於JavaMail實現帶附件的收發郵件網上的例子很多,自己興趣來了,自己也動手嘗試了一番。

其中問題大部分在代碼註釋中,這裏也就不過多描述了,直接上代碼作為記錄,方便以後查閱。

二、工程目錄

技術分享

三、工程代碼

  1、Mail.java

技術分享
package com.xie.util;

import java.util.ArrayList;
import java.util.List;

/** * 表示郵件類,你需要設置:賬戶名和密碼、收件人、抄送(可選)、暗送(可選)、主題、內容,以及附件(可選) * * 在創建了Mail對象之後 * 可以調用它的setSubject()、setContent(),設置主題和正文 * 也可以調用setFrom()和 addToAddress(),設置發件人,和添加收件人。 * 也可以調用addAttch()添加附件 * 創建AttachBean:new AttachBean(new File("..."), "fileName"); */ public class Mail { private String from; //
發件人 private StringBuilder toAddress = new StringBuilder(); //收件人 private StringBuilder ccAddress = new StringBuilder(); //抄送 private StringBuilder bccAddress = new StringBuilder(); //暗送 private String subject;//主題 private String content;//正文 // 附件列表 private List<AttachBean> attachList = new
ArrayList<AttachBean>(); public Mail() {} public Mail(String from, String to) { this(from, to, null, null); } public Mail(String from, String to, String subject, String content) { this.from = from; this.toAddress.append(to); this.subject = subject; this.content = content; } /** * 返回發件人 * @return */ public void setFrom(String from) { this.from = from; } /** * 返回發件人 * @return */ public String getFrom() { return from; } /** * 返回主題 */ public String getSubject() { return subject; } /** * 設置主題 */ public void setSubject(String subject) { this.subject = subject; } /** * 獲取主題內容 */ public String getContent() { return content; } /** * 設置主題內容 * @param content */ public void setContent(String content) { this.content = content; } /** * 獲取收件人 * @return */ public String getToAddress() { return toAddress.toString(); } /** * 獲取抄送 * @return */ public String getCcAddress() { return ccAddress.toString(); } /** * 獲取暗送 * @return */ public String getBccAddress() { return bccAddress.toString(); } /** * 添加收件人,可以是多個收件人 * @param to */ public void addToAddress(String to) { if(this.toAddress.length() > 0) { this.toAddress.append(","); } this.toAddress.append(to); } /** * 添加抄送人,可以是多個抄送人 * @param cc */ public void addCcAddress(String cc) { if(this.ccAddress.length() > 0) { this.ccAddress.append(","); } this.ccAddress.append(cc); } /** * 添加暗送人,可以是多個暗送人 * @param bcc */ public void addBccAddress(String bcc) { if(this.bccAddress.length() > 0) { this.bccAddress.append(","); } this.bccAddress.append(bcc); } /** * 添加附件,可以添加多個附件 * @param attachBean */ public void addAttach(AttachBean attachBean) { this.attachList.add(attachBean); } /** * 獲取所有附件 * @return */ public List<AttachBean> getAttachs() { return this.attachList; } }
View Code

  2、AttachBean.java

技術分享
package com.xie.util;

import java.io.File;

/**
 * 發送附件用
 */

public class AttachBean {
    
    private String cid;
    private File file;
    private String fileName;

    public AttachBean() {

    }

    public AttachBean(File file, String fileName) {
        super();
        this.file = file;
        this.fileName = fileName;
    }
    public String getCid() {
        return cid;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }
    
    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    
}
View Code

  3、MailUtils.java

技術分享
package com.xie.util;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 郵件工具類
 */
public class MailUtils {
    
    public static Session createSession(String host, final String username, final String password, String smtpPort) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", host);        // 指定主機
        prop.setProperty("mail.smtp.auth", "true"); // 指定驗證為true
        
        // SMTP 服務器的端口 (非 SSL 連接的端口一般默認為 25, 可以不添加, 如果開啟了 SSL 連接,
        //                  需要改為對應郵箱的 SMTP 服務器的端口, 具體可查看對應郵箱服務的幫助,
        //                  QQ郵箱的SMTP(SLL)端口為465或587, 其他郵箱自行去查看)
        if(!"".equals(smtpPort) && smtpPort!=null){
            prop.setProperty("mail.smtp.port", smtpPort);
            prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.setProperty("mail.smtp.socketFactory.fallback", "false");
            prop.setProperty("mail.smtp.socketFactory.port", smtpPort);
        }

        // 創建驗證器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
        
        // 獲取session對象
        return Session.getInstance(prop, auth);
    }
    
    /**
     * 發送指定的郵件
     * 
     * @param mail
     */
    public static void send(Session session, final Mail mail) throws MessagingException,
            IOException {

        MimeMessage msg = new MimeMessage(session);// 創建郵件對象
        msg.setFrom(new InternetAddress(mail.getFrom()));// 設置發件人
        msg.addRecipients(RecipientType.TO, mail.getToAddress());// 設置收件人

        // 設置抄送
        String cc = mail.getCcAddress();
        if (!cc.isEmpty()) {
            msg.addRecipients(RecipientType.CC, cc);
        }

        // 設置暗送
        String bcc = mail.getBccAddress();
        if (!bcc.isEmpty()) {
            msg.addRecipients(RecipientType.BCC, bcc);
        }

        msg.setSubject(mail.getSubject());// 設置主題

        MimeMultipart parts = new MimeMultipart();// 創建部件集對象

        MimeBodyPart part = new MimeBodyPart();// 創建一個部件
        part.setContent(mail.getContent(), "text/html;charset=utf-8");// 設置郵件文本內容
        parts.addBodyPart(part);// 把部件添加到部件集中
        
        ///////////////////////////////////////////

        // 添加附件
        List<AttachBean> attachBeanList = mail.getAttachs();// 獲取所有附件
        if (attachBeanList != null) {
            for (AttachBean attach : attachBeanList) {
                MimeBodyPart attachPart = new MimeBodyPart();// 創建一個部件
                attachPart.attachFile(attach.getFile());// 設置附件文件
                attachPart.setFileName(MimeUtility.encodeText(attach
                        .getFileName()));// 設置附件文件名
                String cid = attach.getCid();
                if(cid != null) {
                    attachPart.setContentID(cid);
                }
                parts.addBodyPart(attachPart);
            }
        }

        msg.setContent(parts);// 給郵件設置內容
        Transport.send(msg);// 發郵件
    }
}
View Code

  4、MailUtilsTest.java測試類

技術分享
package com.xie.main;

import java.io.File;
import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.Session;

import org.junit.Test;

import com.xie.util.AttachBean;
import com.xie.util.Mail;
import com.xie.util.MailUtils;


/**
 * @filename MailUtilsTest.java
 * @author xiehongwei
 * @date 2017-7-19 下午4:54:32
 *
 */
public class MailUtilsTest {

    @Test
    public void sendMail() throws MessagingException, IOException{
        /**
         * 1.登錄郵件服務器
         *     MailUtils.createSession(服務器地址,登錄名,密碼,端口);
         *     服務器地址:    發件人郵箱的 SMTP 服務器地址, 必須準確, 不同郵件服務器地址不同, 一般(只是一般, 絕非絕對)格式為: smtp.xxx.com
         *                     (網易163郵箱的 SMTP 服務器地址為: smtp.163.com)
         *     登錄名:        qq號或者其他郵箱賬號,[email protected]
         *     密碼:        一般為授權碼(PS: 某些郵箱服務器為了增加郵箱本身密碼的安全性,給 SMTP 客戶端設置了獨立密碼,並非我們郵箱登錄密碼,
         *                                 開啟SMTP服務的時候會給我們一個授權碼的)
         *     端口:        SMTP 服務器的端口 (非 SSL 連接的端口一般默認為 25, 可以不添加, 如果開啟了 SSL 連接,
         *                                        需要改為對應郵箱的 SMTP 服務器的端口, 具體可查看對應郵箱服務的幫助, 
         *                                       QQ郵箱的SMTP(SLL)端口為465或587, 其他郵箱自行去查看)
         *     
         * 2.創建郵件對象
         *     from:    發件人(郵箱: [email protected]@163.com)
         *     to:        收件人(郵箱: [email protected]@163.com)
         *     subject: 主題(隨意)
         *     content: 正文(隨意)
         *     
         * 3.發郵件
         *     需要第1步得到的session 以及 第2步的郵件對象
         */
     
//        Session session=MailUtils.createSession("smtp.qq.com", "aaa", "pwd", "465");
//        Mail mail=new Mail("[email protected]","[email protected]","測試郵件標題啊","來自qq發送的郵件內容啊");
        Session session=MailUtils.createSession("smtp.163.com", "xxx", "pwd", "");
        Mail mail=new Mail("[email protected]","[email protected],[email protected]","測試郵件標題啊","來自163發送的郵件內容啊");
        
        // 添加附件
        AttachBean attachBean1 = new AttachBean(new File("src/com/xie/file/測試word.doc"), "測試word.doc");
        AttachBean attachBean2 = new AttachBean(new File("src/com/xie/file/atx830.png"), "atx830.png");
        mail.addAttach(attachBean1);
        mail.addAttach(attachBean2);
        
        //發送
        MailUtils.send(session, mail);
        
    }
    
}
View Code

JavaMail實現帶附件的收發郵件