郵件發送接收工具

用到的jar包html

javax.mail-1.5.0.jar,支持jdk1.7.0_12java

這個版本jar包中集成了javax.mail和com.sun.mail【裏邊有ssl須要用到的MailSSLSocketFactory】web

EmailUtil安全

package com.develop.web.util;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailUtil {
    
    private static String DEFAULT_ENCODING = "UTF-8";
    private static Boolean DEFAULT_SSL_ENABLE = false;
    private static String DEFAULT_SMTP_PORT = "25";
    private static String DEFAULT_SMTP_PORT_SSL = "465";
    private static String DEFAULT_POP3_PORT = "110";
    private static String DEFAULT_POP3_PORT_SSL = "995";
    private static String DEFAULT_IMAP_PORT = "143";
    private static String DEFAULT_IMAP_PORT_SSL = "993";
    
    /**
     * 鏈接郵件服務器的參數配置
     * @param entity
     * @return
     */
    private static Properties getProps(EmailEntity entity){
        
        String mailProtocol = "smtp";
        if(entity.getMailProtocol()!=null&&entity.getMailProtocol().trim().length()>0){
            mailProtocol = entity.getMailProtocol().toLowerCase();
        }
        
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        
        if(mailProtocol.contains("pop")){
            return getPOP3(entity);
        }else if(mailProtocol.contains("imap")){
            return getIMAP(entity);
        }else{
            return getSMTP(entity);
        }

    }
    
    /**
     * 發送消息
     * @param entity
     */
    public static void sendEmail(EmailEntity entity){
        
        //設置發信協議
        entity.setMailProtocol("smtp");
        
        //鏈接郵件服務器的參數配置
        Properties props = getProps(entity);
        
        //建立定義整個應用程序所需的環境信息的 Session 對象
        Session session = Session.getInstance(props);
        //設置調試信息在控制檯打印出來
        session.setDebug(true);
        //三、建立郵件的實例對象
        Message msg = getMimeMessage(session, entity);
        //四、根據session對象獲取郵件傳輸對象Transport
        Transport transport  = null;
        try {
            transport = session.getTransport();
            
            //設置發件人的帳戶名和受權碼
            transport.connect(entity.getMailAccount(), entity.getMailAuthCode());
            //發送郵件,併發送到全部收件人地址,message.getAllRecipients() 獲取到的是在建立郵件對象時添加的全部收件人, 抄送人, 密送人
            
            transport.sendMessage(msg,msg.getAllRecipients());
            
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            if(transport!=null){
                //關閉郵件鏈接
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    
    /**
     * 用於發信內容中添加圖片,該圖片路徑須要添加到EmailEntity的圖片路徑中。
     * @param imgPath
     * @return
     */
    public static String addImg(String imgPath){
        String img = "<img src='cid:"+ imgPath +"' />";
        return img;
    }
    
    /**
     * 接收消息
     * @param entity
     * @return
     */
    public static Message[] receiveEmail(EmailEntity entity){
        String mailProtocol = entity.getMailProtocol();
        if(mailProtocol==null||mailProtocol.trim().length()==0){
            mailProtocol = "pop3";
        }
        
        if(!(mailProtocol.contains("pop")||mailProtocol.contains("imap"))){
            System.out.println("非法的收件協議["+mailProtocol+"]");
            return null;
        }
        //設置收件協議
        entity.setMailProtocol(mailProtocol);
        
        //鏈接郵件服務器的參數配置
        Properties props = getProps(entity);
        
        //建立定義整個應用程序所需的環境信息的 Session 對象
        Session session = Session.getInstance(props);
        //設置調試信息在控制檯打印出來
        session.setDebug(true);
        
        Store store = null;
        Folder folder = null;
        Message[] messages = null;
        
        try {

            store = session.getStore(mailProtocol);
            store.connect(entity.getMailAccount(), entity.getMailAuthCode());
            folder = store.getFolder("INBOX");//Sent Messages
            if(folder!=null&&folder.exists()){
                folder.open(Folder.READ_ONLY);
                
                messages = folder.getMessages();
            }
            
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                if(folder!=null){
                    folder.close(false);
                }
                if(store!=null){
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        
        return messages;
    }
    
    /**
     * 得到建立一封郵件的實例對象
     * @param session
     * @param entity
     * @return
     */
    private static MimeMessage getMimeMessage(Session session, EmailEntity entity){
        MimeMessage msg = new MimeMessage(session);
        try {
            //設置發送地址
            msg.setFrom(new InternetAddress(entity.getFromAddress()));
            
            //設置接收地址
            List<String> toAddressList = entity.getToAddressList();
            //若是有多個收件人地址
            if(toAddressList.size()>1){
                InternetAddress[] addressArr= new InternetAddress[toAddressList.size()+1];
                for(int i=0;i<toAddressList.size();i++){
                    addressArr[i] = new InternetAddress(toAddressList.get(i));
                }
                msg.setRecipients(RecipientType.TO, addressArr);
                
            }else if(toAddressList.size()==1){
                msg.setRecipient(RecipientType.TO, new InternetAddress(toAddressList.get(0)));
            }else{
                System.out.println("收件人地址爲空");
            }
            
            //設置抄送地址
            List<String> ccAddressList = entity.getCcAddressList();
            //若是有多個抄送人地址
            if(ccAddressList.size()>1){
                InternetAddress[] addressArr= new InternetAddress[ccAddressList.size()+1];
                for(int i=0;i<ccAddressList.size();i++){
                    addressArr[i] = new InternetAddress(ccAddressList.get(i));
                }
                msg.setRecipients(RecipientType.CC, addressArr);
                
            }else if(ccAddressList.size()==1){
                msg.setRecipient(RecipientType.CC, new InternetAddress(ccAddressList.get(0)));
            }
            
            //設置密送地址
            List<String> bccAddressList = entity.getBccAddressList();
            //若是有多個抄送人地址
            if(bccAddressList.size()>1){
                InternetAddress[] addressArr= new InternetAddress[bccAddressList.size()+1];
                for(int i=0;i<bccAddressList.size();i++){
                    addressArr[i] = new InternetAddress(bccAddressList.get(i));
                }
                msg.setRecipients(RecipientType.BCC, addressArr);
                
            }else if(bccAddressList.size()==1){
                msg.setRecipient(RecipientType.BCC, new InternetAddress(bccAddressList.get(0)));
            }
            
            //設置主題
            String subject = entity.getSubject();
            subject = (subject==null?"":subject);
            
            String mailEncoding = entity.getMailEncoding();
            
            msg.setSubject(subject, (mailEncoding == null?DEFAULT_ENCODING : mailEncoding));
            
            String content = entity.getContent();
            content = (content==null?"":content);
            
            //設置內容
            MimeMultipart contentPart = new MimeMultipart();
            
            //包含文字和圖片的part
            MimeBodyPart text_img_Part = new MimeBodyPart();
            MimeMultipart text_img_multiPart = new MimeMultipart();
            
            //文字內容
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(content, "text/html;charset=" + (mailEncoding == null?DEFAULT_ENCODING : mailEncoding));
            
            text_img_multiPart.addBodyPart(textPart);
            
            //若是有圖片,添加圖片部分
            List<String> imgPathList = entity.getImgPathList();
            if(imgPathList.size()>0){
                for(String imgPath :imgPathList){
                    MimeBodyPart imgPart = new MimeBodyPart();
                    DataHandler dataHandler = new DataHandler(new FileDataSource(imgPath));
                    imgPart.setDataHandler(dataHandler);
                    imgPart.setContentID(imgPath);
                    
                    text_img_multiPart.addBodyPart(imgPart);
                }
                
                text_img_multiPart.setSubType("related");//關聯關係
            }
            
            text_img_Part.setContent(text_img_multiPart);
            
            contentPart.addBodyPart(text_img_Part);
            
            
            List<String> attachmentPathList = entity.getAttachmentPathList();
            if(attachmentPathList.size()>0){
                for(String attachmentPath :attachmentPathList){
                    MimeBodyPart attachmentPart = new MimeBodyPart();
                    DataHandler dataHandler = new DataHandler(new FileDataSource(attachmentPath));
                    attachmentPart.setDataHandler(dataHandler);
                    attachmentPart.setFileName(MimeUtility.encodeText(dataHandler.getName()));
                    
                    contentPart.addBodyPart(attachmentPart);
                }
                
                contentPart.setSubType("mixed");
            }
            
            msg.setContent(contentPart);
            msg.setSentDate(new Date());
            
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        return msg;
    }
    
    
    /** 
    * 獲取SMTP發信配置 
    * 不使用ssl 端口號25
    * 使用ssl 端口465或587
    * @return 
    */ 
    private static Properties getSMTP(EmailEntity entity) {
        //1.默認不使用SSL端口
        Boolean sslEnabled = DEFAULT_SSL_ENABLE;
        String port = DEFAULT_SMTP_PORT;
        Boolean mailUseSSL = entity.getMailUseSSL();
        //2.若是傳入使用SSL參數,則修改成默認SSL端口
        if(mailUseSSL!=null&&mailUseSSL){
            sslEnabled = mailUseSSL;
            port = DEFAULT_SMTP_PORT_SSL;
        }
        //3.若是傳入的服務器端口號,使用傳入的端口
        String mailPort = entity.getMailPort();
        if(mailPort!=null&&mailPort.trim().length()>0){
            port = mailPort;
        }
        
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.port", port);
        props.setProperty("mail.smtp.auth", "true");
        
        if(mailUseSSL!=null&&mailUseSSL){
            // SSL安全鏈接參數 
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", port);
            props.setProperty("mail.smtp.ssl.enable", sslEnabled.toString());
            try {
                //使用的mail-1.5.0版本
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
        
        String mailHost = entity.getMailHost();
        Boolean mailSmtpAuth = entity.getMailSmtpAuth();
        
        if(mailHost!=null&&mailHost.trim().length()>0){
            props.setProperty("mail.smtp.host", mailHost);
        }

        if(mailSmtpAuth!=null){
            props.setProperty("mail.smtp.auth", mailSmtpAuth.toString());
        }
        
        return props; 
    }
    
    /** 
    * 獲取POP3收信配置 
    * 不使用ssl 端口號110
    * 使用ssl 端口號 993
    * @return 
    */ 
    private static Properties getPOP3(EmailEntity entity) {
        //1.默認不使用SSL端口
        Boolean sslEnabled = DEFAULT_SSL_ENABLE;
        String port = DEFAULT_POP3_PORT;
        Boolean mailUseSSL = entity.getMailUseSSL();
        //2.若是傳入使用SSL參數,則修改成默認SSL端口
        if(mailUseSSL!=null&&mailUseSSL){
            sslEnabled = mailUseSSL;
            port = DEFAULT_POP3_PORT_SSL;
        }
        //3.若是傳入的服務器端口號,使用傳入的端口
        String mailPort = entity.getMailPort();
        if(mailPort!=null&&mailPort.trim().length()>0){
            port = mailPort;
        }
        
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");
        props.setProperty("mail.pop3.host", "pop.qq.com");
        props.setProperty("mail.pop3.port", port);
        
        if(mailUseSSL!=null&&mailUseSSL){
            // SSL安全鏈接參數 
            props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.pop3.socketFactory.fallback", "false");
            props.setProperty("mail.pop3.socketFactory.port", port);
            props.setProperty("mail.pop3.ssl.enable", sslEnabled.toString());
            try {
                //使用的mail-1.5.0版本
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }

        
        String mailHost = entity.getMailHost();
        
        if(mailHost!=null&&mailHost.trim().length()>0){
            props.setProperty("mail.pop3.host", mailHost);
        }
        
        return props;
    }
    
    /** 
    * 獲取IMAP收信配置 
    * 不使用ssl 端口號143
    * 使用ssl 端口號993
    * @return 
    */ 
    private static Properties getIMAP(EmailEntity entity) {
        //1.默認不使用SSL端口
        Boolean sslEnabled = DEFAULT_SSL_ENABLE;
        String port = DEFAULT_IMAP_PORT;
        Boolean mailUseSSL = entity.getMailUseSSL();
        //2.若是傳入使用SSL參數,則修改成默認SSL端口
        if(mailUseSSL!=null&&mailUseSSL){
            sslEnabled = mailUseSSL;
            port = DEFAULT_IMAP_PORT_SSL;
        }
        //3.若是傳入的服務器端口號,使用傳入的端口
        String mailPort = entity.getMailPort();
        if(mailPort!=null&&mailPort.trim().length()>0){
            port = mailPort;
        }
        
        Properties props = new Properties(); 
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.qq.com");
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.auth.login.disable", "true");
        
        if(mailUseSSL!=null&&mailUseSSL){
            // SSL安全鏈接參數 
            props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.imap.socketFactory.port", port);
            props.setProperty("mail.imap.ssl.enable", sslEnabled.toString());
            try {
                //使用的mail-1.5.0版本
                MailSSLSocketFactory sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
        
        String mailHost = entity.getMailHost();
        
        if(mailHost!=null&&mailHost.trim().length()>0){
            props.setProperty("mail.imap.host", mailHost);
        }
        
        return props;
    }
    
    
    
    public static void main(String[] args) {
        
        EmailEntity entity = new EmailEntity();
        entity.setMailProtocol("pop3");
        
        List<String> list = new ArrayList<String>();
        list.add("987*****1@qq.com");
        
        entity.setFromAddress("123*****9@qq.com");
        entity.setToAddressList(list);
        entity.setMailAccount("123*****9@qq.com");
        entity.setMailAuthCode("aaikaetllecaje");//受權碼
        entity.setSubject("個人圖片");
        entity.setContent("這是一張圖片<br/><a href='#'>"+addImg("D:/test/test.jpg")+"</a>");
        
        List<String> imgList = new ArrayList<String>();
        imgList.add("D:/test/test.jpg");
        entity.setImgPathList(imgList);
        
        List<String> fileList = new ArrayList<String>();
        fileList.add("D:/test/test.rar");
//        fileList.add("D:/test/測試文件.rar");
//        fileList.add("D:/test/test.jpg");
        entity.setAttachmentPathList(fileList);
        
        sendEmail(entity);
        
//        receiveEmail(entity);
    }
}

 

EmailEntity服務器

package com.develop.web.util;

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

public class EmailEntity {
    //郵件編碼
    private String mailEncoding;
    //郵件收發協議:smtp發信協議;pop3/imap收信協議
    private String mailProtocol;
    //郵件服務器地址
    private String mailHost;
    //郵件服務器端口
    private String mailPort;
    //郵件發信
    private Boolean mailSmtpAuth;
    //郵件是否啓用ssl
    private Boolean mailUseSSL;
    //帳戶
    private String mailAccount;
    //受權碼或密碼
    private String mailAuthCode;
    //發信人地址
    private String fromAddress;
    //收信人地址-可多個
    private List<String> toAddressList = new ArrayList<String>(0);
    //抄送的地址-可多個
    private List<String> ccAddressList = new ArrayList<String>(0);
    //密送的地址-可多個
    private List<String> bccAddressList = new ArrayList<String>(0);
    //郵件主題
    private String subject;
    //添加的圖片路徑
    private List<String> imgPathList = new ArrayList<String>(0);
    //郵件的文本內容
    private String content;
    //附件路徑
    private List<String> attachmentPathList = new ArrayList<String>(0);
    
    public String getMailEncoding() {
        return mailEncoding;
    }
    public void setMailEncoding(String mailEncoding) {
        this.mailEncoding = mailEncoding;
    }
    public String getMailProtocol() {
        return mailProtocol;
    }
    public void setMailProtocol(String mailProtocol) {
        this.mailProtocol = mailProtocol;
    }
    public String getMailHost() {
        return mailHost;
    }
    public void setMailHost(String mailHost) {
        this.mailHost = mailHost;
    }
    public String getMailPort() {
        return mailPort;
    }
    public void setMailPort(String mailPort) {
        this.mailPort = mailPort;
    }
    public Boolean getMailSmtpAuth() {
        return mailSmtpAuth;
    }
    public void setMailSmtpAuth(Boolean mailSmtpAuth) {
        this.mailSmtpAuth = mailSmtpAuth;
    }
    public Boolean getMailUseSSL() {
        return mailUseSSL;
    }
    public void setMailUseSSL(Boolean mailUseSSL) {
        this.mailUseSSL = mailUseSSL;
    }
    public String getMailAccount() {
        return mailAccount;
    }
    public void setMailAccount(String mailAccount) {
        this.mailAccount = mailAccount;
    }
    public String getMailAuthCode() {
        return mailAuthCode;
    }
    public void setMailAuthCode(String mailAuthCode) {
        this.mailAuthCode = mailAuthCode;
    }
    public String getFromAddress() {
        return fromAddress;
    }
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }
    public List<String> getToAddressList() {
        return toAddressList;
    }
    public void setToAddressList(List<String> toAddressList) {
        this.toAddressList = toAddressList;
    }
    public List<String> getCcAddressList() {
        return ccAddressList;
    }
    public void setCcAddressList(List<String> ccAddressList) {
        this.ccAddressList = ccAddressList;
    }
    public List<String> getBccAddressList() {
        return bccAddressList;
    }
    public void setBccAddressList(List<String> bccAddressList) {
        this.bccAddressList = bccAddressList;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public List<String> getImgPathList() {
        return imgPathList;
    }
    public void setImgPathList(List<String> imgPathList) {
        this.imgPathList = imgPathList;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List<String> getAttachmentPathList() {
        return attachmentPathList;
    }
    public void setAttachmentPathList(List<String> attachmentPathList) {
        this.attachmentPathList = attachmentPathList;
    }
    
    


}
相關文章
相關標籤/搜索