邮件发送接收工具

用到的jar包

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

这个版本jar包中集成了javax.mail和com.sun.mail【里边有ssl需要用到的MailSSLSocketFactory】

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);
        //3、创建邮件的实例对象
        Message msg = getMimeMessage(session, entity);
        //4、根据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;
    }
    
    


}
原文地址:https://www.cnblogs.com/jinzhiming/p/10825592.html