javamail接收邮件(较全)工具类_javax.mail 收取邮件工具类-程序员宅基地

技术标签: java  mail  工具  邮件  接收  

直接代码


import java.io.*;   
import java.text.*;   
import java.util.*;   
import javax.mail.*;   
import javax.mail.internet.*;   
  
/**  
 * 有一封邮件就需要建立一个ReciveMail对象  
 */  
public class ReciveOneMail {   
    private MimeMessage mimeMessage = null;   
    private String saveAttachPath = ""; //附件下载后的存放目录   
    private StringBuffer bodytext = new StringBuffer();//存放邮件内容   
    private String dateformat = "yy-MM-dd HH:mm"; //默认的日前显示格式   
  
    public ReciveOneMail(MimeMessage mimeMessage) {   
        this.mimeMessage = mimeMessage;   
    }   
  
    public void setMimeMessage(MimeMessage mimeMessage) {   
        this.mimeMessage = mimeMessage;   
    }   
  
    /**  
     * 获得发件人的地址和姓名  
     */  
    public String getFrom() throws Exception {   
        InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();   
        String from = address[0].getAddress();   
        if (from == null)   
            from = "";   
        String personal = address[0].getPersonal();   
        if (personal == null)   
            personal = "";   
        String fromaddr = personal + "<" + from + ">";   
        return fromaddr;   
    }   
  
    /**  
     * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址  
     */  
    public String getMailAddress(String type) throws Exception {   
        String mailaddr = "";   
        String addtype = type.toUpperCase();   
        InternetAddress[] address = null;   
        if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {   
            if (addtype.equals("TO")) {   
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);   
            } else if (addtype.equals("CC")) {   
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);   
            } else {   
                address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);   
            }   
            if (address != null) {   
                for (int i = 0; i < address.length; i++) {   
                    String email = address[i].getAddress();   
                    if (email == null)   
                        email = "";   
                    else {   
                        email = MimeUtility.decodeText(email);   
                    }   
                    String personal = address[i].getPersonal();   
                    if (personal == null)   
                        personal = "";   
                    else {   
                        personal = MimeUtility.decodeText(personal);   
                    }   
                    String compositeto = personal + "<" + email + ">";   
                    mailaddr += "," + compositeto;   
                }   
                mailaddr = mailaddr.substring(1);   
            }   
        } else {   
            throw new Exception("Error emailaddr type!");   
        }   
        return mailaddr;   
    }   
  
    /**  
     * 获得邮件主题  
     */  
    public String getSubject() throws MessagingException {   
        String subject = "";   
        try {   
            subject = MimeUtility.decodeText(mimeMessage.getSubject());   
            if (subject == null)   
                subject = "";   
        } catch (Exception exce) {}   
        return subject;   
    }   
  
    /**  
     * 获得邮件发送日期  
     */  
    public String getSentDate() throws Exception {   
        Date sentdate = mimeMessage.getSentDate();   
        SimpleDateFormat format = new SimpleDateFormat(dateformat);   
        return format.format(sentdate);   
    }   
  
    /**  
     * 获得邮件正文内容  
     */  
    public String getBodyText() {   
        return bodytext.toString();   
    }   
  
    /**  
     * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析  
     */  
    public void getMailContent(Part part) throws Exception {   
        String contenttype = part.getContentType();   
        int nameindex = contenttype.indexOf("name");   
        boolean conname = false;   
        if (nameindex != -1)   
            conname = true;   
        System.out.println("CONTENTTYPE: " + contenttype);   
        if (part.isMimeType("text/plain") && !conname) {   
            bodytext.append((String) part.getContent());   
        } else if (part.isMimeType("text/html") && !conname) {   
            bodytext.append((String) part.getContent());   
        } else if (part.isMimeType("multipart/*")) {   
            Multipart multipart = (Multipart) part.getContent();   
            int counts = multipart.getCount();   
            for (int i = 0; i < counts; i++) {   
                getMailContent(multipart.getBodyPart(i));   
            }   
        } else if (part.isMimeType("message/rfc822")) {   
            getMailContent((Part) part.getContent());   
        } else {}   
    }   
  
    /**   
     * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"  
     */   
    public boolean getReplySign() throws MessagingException {   
        boolean replysign = false;   
        String needreply[] = mimeMessage   
                .getHeader("Disposition-Notification-To");   
        if (needreply != null) {   
            replysign = true;   
        }   
        return replysign;   
    }   
  
    /**  
     * 获得此邮件的Message-ID  
     */  
    public String getMessageId() throws MessagingException {   
        return mimeMessage.getMessageID();   
    }   
  
    /**  
     * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】  
     */  
    public boolean isNew() throws MessagingException {   
        boolean isnew = false;   
        Flags flags = ((Message) mimeMessage).getFlags();   
        Flags.Flag[] flag = flags.getSystemFlags();   
        System.out.println("flags's length: " + flag.length);   
        for (int i = 0; i < flag.length; i++) {   
            if (flag[i] == Flags.Flag.SEEN) {   
                isnew = true;   
                System.out.println("seen Message.......");   
                break;   
            }   
        }   
        return isnew;   
    }   
  
    /**  
     * 判断此邮件是否包含附件  
     */  
    public boolean isContainAttach(Part part) throws Exception {   
        boolean attachflag = false;   
        String contentType = part.getContentType();   
        if (part.isMimeType("multipart/*")) {   
            Multipart mp = (Multipart) part.getContent();   
            for (int i = 0; i < mp.getCount(); i++) {   
                BodyPart mpart = mp.getBodyPart(i);   
                String disposition = mpart.getDisposition();   
                if ((disposition != null)   
                        && ((disposition.equals(Part.ATTACHMENT)) || (disposition   
                                .equals(Part.INLINE))))   
                    attachflag = true;   
                else if (mpart.isMimeType("multipart/*")) {   
                    attachflag = isContainAttach((Part) mpart);   
                } else {   
                    String contype = mpart.getContentType();   
                    if (contype.toLowerCase().indexOf("application") != -1)   
                        attachflag = true;   
                    if (contype.toLowerCase().indexOf("name") != -1)   
                        attachflag = true;   
                }   
            }   
        } else if (part.isMimeType("message/rfc822")) {   
            attachflag = isContainAttach((Part) part.getContent());   
        }   
        return attachflag;   
    }   
  
    /**   
     * 【保存附件】   
     */   
    public void saveAttachMent(Part part) throws Exception {   
        String fileName = "";   
        if (part.isMimeType("multipart/*")) {   
            Multipart mp = (Multipart) part.getContent();   
            for (int i = 0; i < mp.getCount(); i++) {   
                BodyPart mpart = mp.getBodyPart(i);   
                String disposition = mpart.getDisposition();   
                if ((disposition != null)   
                        && ((disposition.equals(Part.ATTACHMENT)) || (disposition   
                                .equals(Part.INLINE)))) {   
                    fileName = mpart.getFileName();   
                    if (fileName.toLowerCase().indexOf("gb2312") != -1) {   
                        fileName = MimeUtility.decodeText(fileName);   
                    }   
                    saveFile(fileName, mpart.getInputStream());   
                } else if (mpart.isMimeType("multipart/*")) {   
                    saveAttachMent(mpart);   
                } else {   
                    fileName = mpart.getFileName();   
                    if ((fileName != null)   
                            && (fileName.toLowerCase().indexOf("GB2312") != -1)) {   
                        fileName = MimeUtility.decodeText(fileName);   
                        saveFile(fileName, mpart.getInputStream());   
                    }   
                }   
            }   
        } else if (part.isMimeType("message/rfc822")) {   
            saveAttachMent((Part) part.getContent());   
        }   
    }   
  
    /**   
     * 【设置附件存放路径】   
     */   
  
    public void setAttachPath(String attachpath) {   
        this.saveAttachPath = attachpath;   
    }   
  
    /**  
     * 【设置日期显示格式】  
     */  
    public void setDateFormat(String format) throws Exception {   
        this.dateformat = format;   
    }   
  
    /**  
     * 【获得附件存放路径】  
     */  
    public String getAttachPath() {   
        return saveAttachPath;   
    }   
  
    /**  
     * 【真正的保存附件到指定目录里】  
     */  
    private void saveFile(String fileName, InputStream in) throws Exception {   
        String osName = System.getProperty("os.name");   
        String storedir = getAttachPath();   
        String separator = "";   
        if (osName == null)   
            osName = "";   
        if (osName.toLowerCase().indexOf("win") != -1) {   
            separator = "\\";  
            if (storedir == null || storedir.equals(""))  
                storedir = "c:\\tmp";  
        } else {  
            separator = "/";  
            storedir = "/tmp";  
        }  
        File storefile = new File(storedir + separator + fileName);  
        System.out.println("storefile's path: " + storefile.toString());  
        // for(int i=0;storefile.exists();i++){  
        // storefile = new File(storedir+separator+fileName+i);  
        // }  
        BufferedOutputStream bos = null;  
        BufferedInputStream bis = null;  
        try {  
            bos = new BufferedOutputStream(new FileOutputStream(storefile));  
            bis = new BufferedInputStream(in);  
            int c;  
            while ((c = bis.read()) != -1) {  
                bos.write(c);  
                bos.flush();  
            }  
        } catch (Exception exception) {  
            exception.printStackTrace();  
            throw new Exception("文件保存失败!");  
        } finally {  
            bos.close();  
            bis.close();  
        }  
    }  
 
    /**  
     * PraseMimeMessage类测试  
     */  
    public static void main(String args[]) throws Exception {  
        Properties props = System.getProperties();  
        props.put("mail.smtp.host", "smtp.163.com");  
        props.put("mail.smtp.auth", "true");  
        Session session = Session.getDefaultInstance(props, null);  
        URLName urln = new URLName("pop3", "pop3.163.com", 110, null,  
                "xiangzhengyan", "pass");  
        Store store = session.getStore(urln);  
        store.connect();  
        Folder folder = store.getFolder("INBOX");  
        folder.open(Folder.READ_ONLY);  
        Message message[] = folder.getMessages();  
        System.out.println("Messages's length: " + message.length);  
        ReciveOneMail pmm = null;  
        for (int i = 0; i < message.length; i++) {  
            System.out.println("======================");  
            pmm = new ReciveOneMail((MimeMessage) message[i]);  
            System.out.println("Message " + i + " subject: " + pmm.getSubject());  
            System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());  
            System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());  
            System.out.println("Message " + i + " hasRead: " + pmm.isNew());  
            System.out.println("Message " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i]));  
            System.out.println("Message " + i + " form: " + pmm.getFrom());  
            System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));  
            System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));  
            System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));  
            pmm.setDateFormat("yy年MM月dd日 HH:mm");  
            System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());  
            System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());  
            // 获得邮件内容===============  
            pmm.getMailContent((Part) message[i]);  
            System.out.println("Message " + i + " bodycontent: \r\n"  
                    + pmm.getBodyText());  
            pmm.setAttachPath("c:\\");   
            pmm.saveAttachMent((Part) message[i]);   
        }   
    }   
}  


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/hj7jay/article/details/51258538

智能推荐

VB6-该部件的许可证信息没有找到的解决方法_vb licenses-程序员宅基地

文章浏览阅读9.2k次。VB6添加控件时提示 该部件的许可证信息没有找到,将以下文件保存为注册表文件并导入Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Licenses] @="Licensing: Copying the keys may be a violation of established copyrights._vb licenses

android agentweb进度,AgentWeb-Android-H5混合开发-程序员宅基地

文章浏览阅读301次。简介agentweb 是对webview进行的又一层封装较为轻量级所以基本的开发流程大致和webview原理相似将html5文件方入asset文件夹下,访问路径为final private String CoachFile = "file:///android_asset/teacher/info-teacher.html";运行demo此demo使用了bintray/Jcenter 这个东西Jc..._agentweb token

【Phone ECC】紧急号码的管理及客制化方法_sim卡 ecclist-程序员宅基地

文章浏览阅读614次。[Android Version]Android 5.0/5.1 (L)Android 6.0 (M)Android 7.0(N)Android 8.0(O)[DESCRIPTION]L及之后的版本紧急号码Customer的部分改成了在XML文件中来配置,文件的路径: alps\vendor\mediatek\proprietary\external\EccL..._sim卡 ecclist

BCrypt 加密实现_写一个bcrypt-程序员宅基地

文章浏览阅读1.1k次。Bcrypt百度百科:1、 bcrypt,是一个跨平台的文件加密工具。由它加密的文件可在所有支持的操作系统和处理器上进行转移。它的口令必须是8至56个字符,并将在内部被转化为448位的密钥。2、bcrypt算法相对来说是运算比较慢的算法,在密码学界有句常话:越慢的算法越安全。算法越算,黑客破解成本越高.通过salt和const这两个值来减缓加密过程,ta的加密时间(百ms级)远远超过md5(大概1..._写一个bcrypt

LaTeX中的中英文字体设置、混排_latex英文字体-程序员宅基地

文章浏览阅读2.4w次,点赞14次,收藏87次。LaTeX中英文字体设置、混排,ctex宏包引用_latex英文字体

uni-app 消息推送功能UniPush_uniapp消息推送功能-程序员宅基地

文章浏览阅读5.7k次,点赞2次,收藏20次。这里用的是uni-app自带的UniPush1.0(个推服务),所以只针对UniPush1.0介绍实现步骤。当然现在已经出了UniPush2.0(HBuilderX 3.5.1及其以上版本支持),新项目的话还是推荐使用UniPush2.0。如果要使用UniPush2.0,请移步 UniPush 2.0 使用指南。_uniapp消息推送功能

随便推点

java财务对账系统设计_对账系统设计-程序员宅基地

文章浏览阅读1.4k次。更多支付内容请移步个人站:YKBLog.top对账整体设计从整体来看,按照时序维度的先后,系统对账主要分为三阶段的工作。分别是数据准备、数据核对和差错处理。数据准备细分一下,又分为文件获取、文件解析、数据清洗。在对账专业概念中,数据核对和差错处理又叫轧账和平账。具体设计脑图如下:check-arch.png对账各个模块设计数据准备数据准备,顾名思义,我们需要把对账所需的全部数据,接入到我们的对账系..._java 对账实战思路

Python新姿势:用魔法方法玩转对象-程序员宅基地

文章浏览阅读887次,点赞23次,收藏17次。Python中魔法方法(magic method)其实就是那些被双下划线包围的方法,比如__init____str__等等。这些魔法方法为类添加了**“魔力”,让我们可以在面向对象编程中用更加简洁的代码来操作对象。本篇根据面向对象编程的一些场景来介绍常用的魔法方法**。Python的魔法方法很多,本文只是列举了其中很少的一部分,github上有一个示例python。

小程序云开发 上传图片到云存储_微信小程序上传图片到云存储-程序员宅基地

文章浏览阅读9.4k次,点赞20次,收藏102次。在学习了小程序云开发后,遇到了开发中常见的图片上传,今天简单的记录总结下在云开发中如何实现图片上传到云存储中。_微信小程序上传图片到云存储

ftp服务器上传文件频率,ftp服务器上传文件速度多少-程序员宅基地

文章浏览阅读1k次。ftp服务器上传文件速度多少 内容精选换一换华为云帮助中心,为用户提供产品简介、价格说明、购买指南、用户指南、API参考、最佳实践、常见问题、视频帮助等技术文档,帮助您快速上手使用华为云服务。使用FTP上传文件时,写入失败,文件传输失败。该文档适用于Windows系统上的FTP服务。FTP服务端在NAT环境下,客户端需使用被动模式连接服务端。在这种情况下,服务端的IP地址无法从路由器外部访问,所以..._c# ftp上传速度默认多少

简单理解磁盘结构-程序员宅基地

文章浏览阅读3.6w次,点赞126次,收藏373次。    偶然看到一道笔试题,所以简单整理了一下磁盘的结构。本文主要介绍传统的磁盘结构,包括盘面、磁道、扇区、柱面、读写数据过程的概念,最后给出所遇到的笔试题。磁盘结构    传统的硬盘盘结构是像下图样子的,它有一个或多个盘片,用于存储数据,盘片多采用铝合金材料;中间有一个主轴,所有的盘片都绕着这个主轴转动,一个组合臂上面有多个磁头臂,每个磁头臂上面都有一个磁头,负责读写数据。..._磁盘结构

python数组(list) 求交集、并集、差集_python计算四个数组的交集代码-程序员宅基地

文章浏览阅读1.4w次,点赞7次,收藏16次。两个集合: a = [1,2,3,4,5,6] b = [3,5,7]1.求交集 方式一: intersection = [i for i in a if i in b] intersection = list(set(a).intersection(set(b))) 结果: [3, 5]2.求并集 union= list(set(a).u..._python计算四个数组的交集代码

推荐文章

热门文章

相关标签