javamail 收发邮件

来源:互联网 发布:激光笔软件 编辑:程序博客网 时间:2024/05/24 23:15


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.FolderNotFoundException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.imap.IMAPFolder;

/**
 *
 * <p>
 * Title: MailManager
 * </p>
 * <p>
 * Description: 邮件服务
 * </p>
 *
 * @author xugh
 * @date Aug 27, 2015 8:44:53 AM
 */
public class MailUtil {

    public static String HOST = "192.168.0.44";

    /**
     * 发送邮件
     *
     * @param account
     *            账户
     * @param pwd
     *            密码
     * @param mail
     *            邮件
     * @throws Exception
     */
    public static void sendMessage(String account, String pwd, SampleMail mail) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", HOST);
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        // 使用JavaMail发送邮件的5个步骤
        // 1、创建session
        Session session = Session.getInstance(prop);
        // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        //session.setDebug(true);
        // 2、通过session得到transport对象
        try {
            Transport ts = session.getTransport();
            // 3、连上邮件服务器
            ts.connect(HOST, account, pwd);
            // 4创建邮件
            Message message = createAttachMail(session, mail);
            // 5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    }

    /**
     * 生成邮件对象
     *
     * @param session
     * @param mail
     * @return
     * @throws Exception
     */
    private static MimeMessage createAttachMail(Session session, SampleMail mail) {
        MimeMessage message = new MimeMessage(session);
        // 设置邮件的基本信息
        // 发件人
        try {
            message.setFrom(new InternetAddress(mail.getFrom()));
            // 收件人
            List<String> toList = mail.getToList();
            for (String to : toList) {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(
                        to));
            }
            // 抄送人
            List<String> ccList = mail.getCcList();
            for (String cc : ccList) {
                message.setRecipient(Message.RecipientType.CC, new InternetAddress(
                        cc));
            }
            // 邮件标题
            message.setSubject(mail.getSubject());
            // 创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();
            // 创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(mail.getContent(), "text/html;charset=UTF-8");
            mp.addBodyPart(text);
            List<String> filePathList = mail.getFilePathList();
            if (filePathList != null && filePathList.size() > 0) {
                for (String filePath : filePathList) {
                    DataHandler dh = new DataHandler(new FileDataSource(filePath));
                    // 创建邮件附件
                    MimeBodyPart attach = new MimeBodyPart();
                    attach.setDataHandler(dh);
                    attach.setFileName(MimeUtility.encodeText(dh.getName()));
                    mp.addBodyPart(attach);
                }
            }
            mp.setSubType("mixed");
            message.setContent(mp);
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (AddressException e) {
            
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
        // 返回生成的邮件
        return message;
    }

    
    
    /**
     * 转发邮件
     *
     * @param account
     *            账户
     * @param pwd
     *            密码
     * @param mail
     *            邮件邮件ID
     * @param oldMailId 被转发的
     *
     * @throws Exception
     */
    public static void forwardMessage(String account, String pwd, SampleMail mail,MailEnum mailEnum,long oldMailId) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", HOST);
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        // 使用JavaMail发送邮件的5个步骤
        // 1、创建session
        Session session = Session.getInstance(prop);
        // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        //session.setDebug(true);
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        try {
            // 创建Session实例对象
            Session imapSession = Session.getInstance(props);
            Store store = imapSession.getStore("imap");
            store.connect(HOST, account, pwd);
            // 获得源文件夹
            IMAPFolder folder = null;
            try {
                folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                folder.open(Folder.READ_ONLY);
            } catch (FolderNotFoundException e) {
                folder = (IMAPFolder) store.getFolder("已发送");
                folder.open(Folder.READ_ONLY);
            }
            // 以只读模式打开文件夹
            // 获得邮件
            MimeMessage msg = (MimeMessage) folder.getMessageByUID(oldMailId);
            // 2、通过session得到transport对象
            Transport ts = session.getTransport();
            // 3、连上邮件服务器
            ts.connect(HOST, account, pwd);
            // 4创建邮件
            Message message = createFarwardMail(session, mail,msg);
            // 5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            //Transport.send(message);
            if(ts != null){
                ts.close();    
            }
            // 如果文件夹不为空且已经打开就将其关闭
            if (folder != null && folder.isOpen()) {
                folder.close(false);
            }
            // 如果存储为空且已经打开就将其关闭
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        
    }
    
    
    /**
     * 生成转发邮件对象
     *
     * @param session  MimeMessage msg = (MimeMessage) folder.getMessageByUID(uid);
     * @param mail
     * @param msg 被转发邮件
     * @return
     * @throws Exception
     */
    private static MimeMessage createFarwardMail(Session session, SampleMail mail,MimeMessage msg) {
        MimeMessage message = new MimeMessage(session);
        // 设置邮件的基本信息
        try {
            // 发件人
            message.setFrom(new InternetAddress(mail.getFrom()));
            // 收件人
            List<String> toList = mail.getToList();
            for (String to : toList) {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
            // 抄送人
            List<String> ccList = mail.getCcList();
            for (String cc : ccList) {
                message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
            // 邮件标题
            message.setSubject(mail.getSubject());
            // 创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();
            // 创建邮件正文,为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(mail.getContent(), "text/html;charset=UTF-8");
            mp.addBodyPart(text);
            
            List<String> filePathList = mail.getFilePathList();
            if (filePathList != null && filePathList.size() > 0) {
                for (String filePath : filePathList) {
                    DataHandler dh = new DataHandler(new FileDataSource(filePath));
                    // 创建邮件附件
                    MimeBodyPart attach = new MimeBodyPart();
                    attach.setDataHandler(dh);
                    attach.setFileName(MimeUtility.encodeText(dh.getName()));
                    mp.addBodyPart(attach);
                }
            }
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(msg.getDataHandler());
            mp.addBodyPart(messageBodyPart);
            mp.setSubType("mixed");
            message.setContent(mp);
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (AddressException e) {
            
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
        return message;
    }
    

    /**
     * 删除指定文件夹中的邮件 其实删除之后同时移动邮件到回收站
     *
     * @param account
     *            账号
     * @param pwd
     *            密码
     * @param mailEnum
     *            文件夹
     * @param uid
     *            邮件uid数组
     */
    public static void removeMessage(String account, String pwd, MailEnum mailEnum,long[] uid){
            // 准备连接服务器的会话信息
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            props.setProperty("mail.imap.host", HOST);
            props.setProperty("mail.imap.port", "143");
            // 创建Session实例对象
            Session session = Session.getInstance(props);
            try {
                Store store = session.getStore("imap");
                // 连接邮件服务器
                store.connect(HOST, account, pwd);
                // 获得文件夹
                IMAPFolder folder = null;
                try {
                    folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                } catch (FolderNotFoundException e) {
                    folder = (IMAPFolder) store.getFolder("已发送");
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                }
                
                Folder to_folder = store.getFolder("回收站");
                // 移动邮件
                for (long id : uid) {
                    Message msg = folder.getMessageByUID(id);
                    if(null != msg){
                        Message[] needCopyMsgs = new Message[1];
                        needCopyMsgs[0] = msg;
                        // 将获取的邮件对象复制到其他文件夹中
                        folder.copyMessages(needCopyMsgs, to_folder);
                        // 移动意味着要把原有的邮件删除
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
                // 如果文件夹不为空且已经打开就将其关闭
                if (folder != null && folder.isOpen()) {
                    folder.close(true);
                }
                // 如果其他文件夹不为空着将其关闭
                if (to_folder != null && to_folder.isOpen()) {
                    to_folder.close(true);
                }
                // 如果存储为空且已经打开就将其关闭
                if (store != null && store.isConnected()) {
                    store.close();
                }
            } catch (NoSuchProviderException e) {
                
                e.printStackTrace();
            } catch (MessagingException e) {
                
                e.printStackTrace();
            }
    }

    /**
     * 删除指定文件夹中的邮件 真删除
     *
     * @param account
     *            账号
     * @param pwd
     *            密码
     * @param mailEnum
     *            文件夹
     * @param uid
     *            邮件uid数组
     */
    public static  void deleteMessage(String account, String pwd, MailEnum mailEnum,long[] uid) {
            // 准备连接服务器的会话信息
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            props.setProperty("mail.imap.host", HOST);
            props.setProperty("mail.imap.port", "143");
            // 创建Session实例对象
            Session session = Session.getInstance(props);
            try {
                Store store = session.getStore("imap");
                // 连接邮件服务器
                store.connect(HOST, account, pwd);
                // 获得文件夹
                IMAPFolder folder = null;
                try {
                    folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                } catch (FolderNotFoundException e) {
                    folder = (IMAPFolder) store.getFolder("已发送");
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                }
                
                for (long id : uid) {
                    Message msg = folder.getMessageByUID(id);
                    if(null != msg){
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
                // 如果文件夹不为空且已经打开就将其关闭
                if (folder != null && folder.isOpen()) {
                    folder.close(true);
                }
                // 如果存储为空且已经打开就将其关闭
                if (store != null && store.isConnected()) {
                    store.close();
                }
            } catch (NoSuchProviderException e) {
                
                e.printStackTrace();
            } catch (MessagingException e) {
                
                e.printStackTrace();
            }
    }

    /**
     * 移动邮件
     *
     * @param account
     *            账号
     * @param pwd
     *            密码
     * @param sourceMailEnum
     *            源文件夹
     * @param toMailEnum
     *            目的文件夹
     * @param uid
     *            邮件uid
     */
    public static void moveMessage(String account, String pwd,
            MailEnum sourceMailEnum, MailEnum toMailEnum, long[] uid){
            // 准备连接服务器的会话信息
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            props.setProperty("mail.imap.host", HOST);
            props.setProperty("mail.imap.port", "143");
            // 创建Session实例对象
            Session session = Session.getInstance(props);
            try {
                Store store = session.getStore("imap");
                // 连接邮件服务器
                store.connect(HOST, account, pwd);
                // 获得文件夹
                IMAPFolder folder = null;
                try {
                    folder = (IMAPFolder) store.getFolder(sourceMailEnum.getName());
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                } catch (FolderNotFoundException e) {
                    folder = (IMAPFolder) store.getFolder("已发送");
                    // 以读写模式打开收件箱
                    folder.open(Folder.READ_WRITE);
                }
                
                IMAPFolder to_folder = null;
                try {
                    to_folder = (IMAPFolder) store.getFolder(toMailEnum.getName());
                } catch (FolderNotFoundException e) {
                    to_folder = (IMAPFolder) store.getFolder("已发送");
                }
                // 移动邮件
                for (long id : uid) {
                    Message msg = folder.getMessageByUID(id);
                    if(null != msg){
                            Message[] needCopyMsgs = new Message[1];
                            needCopyMsgs[0] = msg;
                            // 将获取的邮件对象复制到目的文件夹中
                            folder.copyMessages(needCopyMsgs, to_folder);
                            // 移动意味着要把原有的邮件删除
                            msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
                // 如果文件夹不为空且已经打开就将其关闭
                if (folder != null && folder.isOpen()) {
                    folder.close(true);
                }
                // 如果其他文件夹不为空着将其关闭
                if (to_folder != null && to_folder.isOpen()) {
                    to_folder.close(true);
                }
                // 如果存储为空且已经打开就将其关闭
                if (store != null && store.isConnected()) {
                    store.close();
                }
            } catch (NoSuchProviderException e) {
                
                e.printStackTrace();
            } catch (MessagingException e) {
                
                e.printStackTrace();
            }
    }

    public static void getFileName(long uid,Part part, List<AttachmentInfo> list) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent(); // 复杂体邮件
            // 复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                // 获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                // 某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                String filename = null;
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    filename = decodeText(bodyPart.getFileName());
                    AttachmentInfo info = new AttachmentInfo(filename,uid,i);
                    list.add(info);
                } else if (bodyPart.isMimeType("multipart/*")) {
                    getFileName(uid,bodyPart, list);//特别复杂的邮件附件目前下载不了
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        filename = decodeText(bodyPart.getFileName());
                        AttachmentInfo info = new AttachmentInfo(filename,uid,i);
                        list.add(info);
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            getFileName(uid,part, list);
        }
        
    }
    
    /**
     * 根据邮件UId得到邮件详情
     *
     * @param account
     *            用户名
     * @param pwd
     *            密码
     * @return
     * @throws Exception
     */
    public static SampleMail getMessageByUid(String account, String pwd,MailEnum mailEnum, long uid) {
        SampleMail mail = null;
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        // 创建IMAP协议的Store对象
        try {
            Store store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(HOST, account, pwd);
            // 获得收件箱
            IMAPFolder folder = null;
            try {
                folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                // 以只读模式打开文件夹
                folder.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException e) {
                folder = (IMAPFolder) store.getFolder("已发送");
                // 以只读模式打开文件夹
                folder.open(Folder.READ_WRITE);
            }
            
            // 获得收件箱的邮件列表
            MimeMessage msg = (MimeMessage) folder.getMessageByUID(uid);
            if(null != msg){
                    mail = new SampleMail();
                    mail.setId(uid);
                    mail.setSubject(getSubject(msg));// 主题
                    mail.setFrom(getFrom(msg));// 发件人
                    String to = getReceiveAddress(msg, Message.RecipientType.TO);// 收件人
                    String[] toArray = to.split(",");
                    List<String> toList = new ArrayList<String>();
                    for (String arr : toArray) {
                        toList.add(arr);
                    }
                    mail.setToList(toList);
                    String cc = getReceiveAddress(msg, Message.RecipientType.CC);// 抄送人
                    String[] ccArray = cc.split(",");
                    List<String> ccList = new ArrayList<String>();
                    if (ccArray != null && ccArray.length > 0) {
                        for (String arr : ccArray) {
                            ccList.add(arr);
                        }
                    }
                    mail.setCcList(ccList);
                    mail.setCreateTime(getSentDate(msg, null));
                    mail.setSeen(isSeen(msg));
                    mail.setSize(msg.getSize() / 1024);
                    mail.setAttactment(isContainAttachment(msg));
                    List<AttachmentInfo> list = new ArrayList<AttachmentInfo>();
                    getFileName(uid,msg,list);
                    mail.setAttlist(list);
                    //mail.setFileName(fileName.toString());
                    StringBuffer content = new StringBuffer(30);
                    getMailTextContent(msg, content);
                    mail.setContent(content.toString());
                    msg.setFlag(Flags.Flag.SEEN, true);
            }
            // 关闭资源
            // 如果文件夹不为空且已经打开就将其关闭
            if (folder != null && folder.isOpen()) {
                folder.close(true);
            }
            // 如果存储为空且已经打开就将其关闭
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
        return mail;
    }

    /**
     * 得到指定文件夹中的邮件数量
     *
     * @param account
     * @param pwd
     * @param mailEnum
     * @return
     * @throws Exception
     */
    public static int getMessageCount(String account, String pwd,
            MailEnum mailEnum) {
        int totalCount = 0;
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        // 创建IMAP协议的Store对象
        try {
            Store store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(HOST, account, pwd);
            // 获得收件箱
            IMAPFolder folder = null;
            try {
                folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                // 以只读模式打开收件箱
                folder.open(Folder.READ_ONLY);
            } catch (FolderNotFoundException e) {
                folder = (IMAPFolder) store.getFolder("已发送");
                // 以只读模式打开收件箱
                folder.open(Folder.READ_ONLY);
            }
            
            totalCount = folder.getMessageCount();// 得到邮件总数
            // 关闭资源
            if (folder != null && folder.isOpen()) {
                folder.close(true);
            }
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
        return totalCount;
    }

    

    /**
     * 把邮件保存进草稿箱
     * @param message
     */
    public static void saveIntoDraft(String account, String pwd,SampleMail mail) {
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        // 创建IMAP协议的Store对象
        try {
            Store store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(HOST, account, pwd);
            //创建邮件
            Message message = createAttachMail(session, mail);        
            Message[] msgs = new Message[1];
            msgs[0] = message;
            // 获得草稿箱
            IMAPFolder folder = (IMAPFolder) store.getFolder(MailEnum.DRAFTBOX.getName());
            folder.open(Folder.READ_WRITE);
            folder.appendMessages(msgs);
            // 关闭资源
            // 如果文件夹不为空且已经打开就将其关闭
            if (folder != null && folder.isOpen()) {
                folder.close(true);
            }
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
    }
    
    /**
     * 取得指定文件夹中的全部邮件
     *
     * @param account
     *            用户名
     * @param pwd
     *            密码
     * @return
     * @throws Exception
     */
    public static List<SampleMail> reciveMessage(String account, String pwd,
            MailEnum mailEnum) {
        List<SampleMail> list = new ArrayList<SampleMail>();
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        // 创建IMAP协议的Store对象
        try {
            Store store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(HOST, account, pwd);
            // 获得收件箱
            IMAPFolder folder = (IMAPFolder) store.getFolder(mailEnum.getName());
            // 以只读模式打开收件箱
            folder.open(Folder.READ_ONLY);
            // 获得收件箱的邮件列表
            Message[] messages = folder.getMessages();
            // 解析所有邮件
            for (int i = messages.length; i > 0; i--) {
                MimeMessage msg = (MimeMessage) messages[i - 1];
                SampleMail mail = new SampleMail();
                mail.setId(folder.getUID(msg));
                mail.setSubject(getSubject(msg));// 主题
                mail.setFrom(getFrom(msg));// 发件人
                String to = getReceiveAddress(msg, Message.RecipientType.TO);// 收件人
                String[] toArray = to.split(",");
                List<String> toList = new ArrayList<String>();
                for (String arr : toArray) {
                    toList.add(arr);
                }
                mail.setToList(toList);
                String cc = getReceiveAddress(msg, Message.RecipientType.CC);// 抄送人
                String[] ccArray = cc.split(",");
                List<String> ccList = new ArrayList<String>();
                if (ccArray != null && ccArray.length > 0) {
                    for (String arr : ccArray) {
                        ccList.add(arr);
                    }
                }
                mail.setCcList(ccList);
                mail.setCreateTime(getSentDate(msg, null));
                mail.setReceiveTime(getReceivedDate(msg, null));
                mail.setSeen(isSeen(msg));
                mail.setSize(msg.getSize() / 1024);
                list.add(mail);
            }
            // 关闭资源
            // 如果文件夹不为空且已经打开就将其关闭
            if (folder != null && folder.isOpen()) {
                folder.close(true);
            }
            // 如果存储为空且已经打开就将其关闭
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 查询指定文件夹中的邮件列表 支持翻页查询
     *
     * @param account
     *            账号
     * @param pwd
     *            密码
     * @param mailEnum
     *            文件夹类型
     * @param pageIndex
     *            当前页码
     * @param pageSize
     *            页数量
     * @return
     * @throws Exception
     */
    public static List<SampleMail> listMessage(String account, String pwd,
            MailEnum mailEnum, int pageIndex, int pageSize) {
        //System.out.println("1  " + System.currentTimeMillis());
        List<SampleMail> list = new ArrayList<SampleMail>();
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", HOST);
        props.setProperty("mail.imap.port", "143");
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        // 创建IMAP协议的Store对象
        try {
            Store store = session.getStore("imap");
            // 连接邮件服务器
            store.connect(HOST, account, pwd);
            // 获得收件箱
            IMAPFolder folder = null;
            try {
                folder = (IMAPFolder) store.getFolder(mailEnum.getName());
                // 以只读模式打开收件箱
                folder.open(Folder.READ_ONLY);
            } catch (FolderNotFoundException e) {
                folder = (IMAPFolder) store.getFolder("已发送");
                // 以只读模式打开收件箱
                folder.open(Folder.READ_ONLY);
            }
            
            int totalCount = folder.getMessageCount();// 得到邮件总数
            if (pageIndex < 1) {
                pageIndex = 1;
            }
            if (pageSize < 1) {
                pageSize = 10;
            }
            int totalPage = totalCount / pageSize;
            if (( totalPage > 1) && (pageIndex > totalPage)) {
                pageIndex = totalPage + 1;
            }
            // 获得收件箱的邮件列表
            int startIndex = (pageIndex - 1) * pageSize + 1;
            int endIndex = pageIndex * pageSize;
            if (endIndex > totalCount) {
                endIndex = totalCount;
            }
            Message[] messages = folder.getMessages(startIndex, endIndex);
            // 解析邮件
            //long start = System.currentTimeMillis();
            //System.out.println("解析开始: "+ start);
            for (int i = 0; i <  messages.length; i++) {
                //long startn = System.currentTimeMillis();
                MimeMessage msg = (MimeMessage) messages[i];
                SampleMail mail = new SampleMail();
                mail.setId(folder.getUID(msg));
                mail.setSubject(getSubject(msg));// 主题
                //String from = "";
                Address[] froms = msg.getFrom();
                if (froms != null && froms.length > 0){
                    StringBuffer buff = new StringBuffer();
                    for(Address addre:froms){
                        InternetAddress address = (InternetAddress) addre;
                        buff.append(address.getAddress()).append(",");
                    }
                    if(buff.length()>0){
                        buff.deleteCharAt(buff.length()-1);
                    }
                    mail.setFrom(buff.toString());// 发件人
                }
                String to = getReceiveAddress(msg, Message.RecipientType.TO);// 收件人
                String[] toArray = to.split(",");
                List<String> toList = new ArrayList<String>();
                for (String arr : toArray) {
                    toList.add(arr);
                }
                mail.setToList(toList);
                String cc = getReceiveAddress(msg, Message.RecipientType.CC);// 抄送人
                String[] ccArray = cc.split(",");
                List<String> ccList = new ArrayList<String>();
                if (ccArray != null && ccArray.length > 0) {
                    for (String arr : ccArray) {
                        ccList.add(arr);
                    }
                }
                mail.setCcList(ccList);
                mail.setCreateTime(getSentDate(msg, null));
                mail.setReceiveTime(getReceivedDate(msg, null));
                mail.setSeen(isSeen(msg));
                mail.setSize(msg.getSize() / 1024);
                mail.setAttactment(isContainAttachment(msg));
                list.add(mail);
                //System.out.println("解析第 "+ i +"封用时  " + (System.currentTimeMillis() - startn));
            }
            Collections.sort(list, new YoujianComparator());
            //System.out.println("解析结束共用时 " + (System.currentTimeMillis()-start));
            // 关闭资源
            // 如果文件夹不为空且已经打开就将其关闭
            if (folder != null && folder.isOpen()) {
                folder.close(true);
            }
            // 如果存储为空且已经打开就将其关闭
            if (store != null && store.isConnected()) {
                store.close();
            }
        } catch (NoSuchProviderException e) {
            
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (MessagingException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
        //System.out.println("6  " + System.currentTimeMillis());
        return list;
    }
    
    public static void main(String[] args) throws Exception {

    
        
    }

    
    
    
    
    

    /**
     * 获得邮件主题
     *
     * @param msg
     *            邮件内容
     * @return 解码后的邮件主题
     */
    public static String getSubject(MimeMessage msg)
            throws UnsupportedEncodingException, MessagingException {
        String subject = "";
        if (msg.getSubject() != null) {
            subject = MimeUtility.decodeText(msg.getSubject());
        }
        return subject;
    }

    /**
     * 获得邮件发件人
     *
     * @param msg
     *            邮件内容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException,
            UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        if(froms != null && froms.length>0){
            InternetAddress address = (InternetAddress) froms[0];
            String person = address.getPersonal();
            if (person != null) {
                person = MimeUtility.decodeText(person) + " ";
            } else {
                person = "";
            }            
            from = address.getAddress();
        }
        //from = person + "<" + address.getAddress() + ">";
        return from;
    }

    /**
     * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
     * <p>
     * Message.RecipientType.TO 收件人
     * </p>
     * <p>
     * Message.RecipientType.CC 抄送
     * </p>
     * <p>
     * Message.RecipientType.BCC 密送
     * </p>
     *
     * @param msg
     *            邮件内容
     * @param type
     *            收件人类型
     * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
     * @throws MessagingException
     */
    public static String getReceiveAddress(MimeMessage msg,
            Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }
        if (addresss != null && addresss.length > 0) {
            for (Address address : addresss) {
                InternetAddress internetAddress = (InternetAddress) address;
                receiveAddress.append(internetAddress.toUnicodeString())
                        .append(",");
            }
            receiveAddress.deleteCharAt(receiveAddress.length() - 1); // 删除最后一个逗号
        }
        return receiveAddress.toString();
    }

    /**
     * 获得邮件发送时间
     *
     * @param msg
     *            邮件内容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern)
            throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy-MM-dd HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 获得邮件接收时间
     *
     * @param msg
     *            邮件内容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getReceivedDate(MimeMessage msg, String pattern)
            throws MessagingException {
        Date receivedDate = msg.getReceivedDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy-MM-dd HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判断邮件中是否包含附件
     *
     * @param msg
     *            邮件内容
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part)
            throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp
                                .equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag)
                    break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }
        return flag;
    }

    /**
     * 判断邮件是否已读 www.2cto.com
     *
     * @param msg
     *            邮件内容
     * @return 如果邮件已读返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判断邮件是否需要阅读回执
     *
     * @param msg
     *            邮件内容
     * @return 需要回执返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg)
            throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 获得邮件的优先级
     *
     * @param msg
     *            邮件内容
     * @return 1(High):紧急 3:普通(Normal) 5:低(Low)
     * @throws MessagingException
     */
    public static String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[0];
            if (headerPriority.indexOf("1") != -1
                    || headerPriority.indexOf("High") != -1)
                priority = "紧急";
            else if (headerPriority.indexOf("5") != -1
                    || headerPriority.indexOf("Low") != -1)
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    }

    /**
     * 获得邮件文本内容
     *
     * @param part
     *            邮件体
     * @param content
     *            存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content)
            throws MessagingException, IOException {
        // 如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    /**
     * 保存附件
     *
     * @param part
     *            邮件中多个组合体中的其中一个组合体
     * @param destDir
     *            附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir)
            throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent(); // 复杂体邮件
            // 复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                // 获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                // 某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp
                                .equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1
                            || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir,
                                decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     *
     * @param is
     *            输入流
     * @param fileName
     *            文件名
     * @param destDir
     *            文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     *
     * @param encodeText
     *            解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText)
            throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }

}



public class SampleMail {

    private long id;//标识
    private String subject;//主题
    private String content;//内容
    private String from;//发件人
    private List<String> toList = new ArrayList<String>();//收件人集合
    private List<String> ccList = new ArrayList<String>();//抄送人集合    
    private List<String> filePathList = new ArrayList<String>();//附件路径集合
    
    private boolean isSeen;//是否已读
    private boolean isAttactment;//是否有附件
    private int size;//邮件大小 kb
    private String createTime;//创建时间
    private String receiveTime;//接收时间
    
    private List<AttachmentInfo> attlist;//附件信息集合
    public SampleMail() {
        super();
        // TODO Auto-generated constructor stub
    }
    public SampleMail(String subject, String content, String from,
            List<String> toList, List<String> ccList, List<String> filePathList) {
        super();
        this.subject = subject;
        this.content = content;
        this.from = from;
        this.toList = toList;
        this.ccList = ccList;
        this.filePathList = filePathList;
    }
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public List<String> getToList() {
        return toList;
    }
    public void setToList(List<String> toList) {
        this.toList = toList;
    }
    public List<String> getCcList() {
        return ccList;
    }
    public void setCcList(List<String> ccList) {
        this.ccList = ccList;
    }
    public List<String> getFilePathList() {
        return filePathList;
    }
    public void setFilePathList(List<String> filePathList) {
        this.filePathList = filePathList;
    }
    
    public boolean isSeen() {
        return isSeen;
    }
    public void setSeen(boolean isSeen) {
        this.isSeen = isSeen;
    }
    public boolean isAttactment() {
        return isAttactment;
    }
    public void setAttactment(boolean isAttactment) {
        this.isAttactment = isAttactment;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }
    public String getReceiveTime() {
        return receiveTime;
    }
    public void setReceiveTime(String receiveTime) {
        this.receiveTime = receiveTime;
    }
    public List<AttachmentInfo> getAttlist() {
        return attlist;
    }
    public void setAttlist(List<AttachmentInfo> attlist) {
        this.attlist = attlist;
    }
    
    
    
}




0 0