关闭

JAVAMail 使用imap协议分析邮件

标签: javamail邮箱邮件
136人阅读 评论(0) 收藏 举报
分类:

准备内容

这里仅以扣扣邮箱为例,首先,登录扣扣邮箱把imap协议开启,并记下授权码(这个过程,不会请百度),这个授权码是用来代替密码登陆的,注意:扣扣邮箱开启imap协议必须先设置独立密码。

下载javamail的jar包填入工程中。

注意事项

应该用SSL登录,一般的方式登陆(http)会进不去,javamail把邮件分解成若干个结构(依次递归分析就可以了),这个代码理会详细展示。

附代码:

package test;




import javax.mail.*;
import javax.mail.internet.InternetAddress;
import java.io.*;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by rightHead on 2016/8/15.
 */
public class MailTest {

    private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private List<Bean> list;
    private Bean bean;
    private String cate = "E:/";
    private String name, pass;  //  邮箱地址 和 授权码

    public List<Bean> getList() {
        return list;
    }

    public void setParameter(String name, String pass, String road){
        cate = road;
        this.name = name;
        this.pass = pass;
    }
    public void start(){


        list = new ArrayList<>();
        getMails(name, pass);

    }

    public boolean connect(){
        return connectTest(name, pass);
    }
    private boolean connectTest(String username, String pass){
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = System.getProperties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.qq.com");
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.socketFactory.port", "993");

        Session session = Session.getDefaultInstance(props,null);

        URLName urln = new URLName("imap","imap.qq.com",993,null,
                username, pass);
        boolean f = false;

        Folder inbox = null;
        try{
            Store store = session.getStore(urln);
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            f = inbox.exists();
        }catch (MessagingException e){
            e.printStackTrace();
        }
        return f;
    }
    public String getMails(String username,String pass){
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = System.getProperties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.qq.com");
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.socketFactory.port", "993");

        Session session = Session.getDefaultInstance(props,null);

        URLName urln = new URLName("imap","imap.qq.com",993,null,
                username, pass);

        Store store = null;
        String msg = "";

        Folder inbox = null;
        try {
            store = session.getStore(urln);
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            Message[] messages = inbox.getMessages();
            inbox.fetch(messages, profile);
            System.out.println(messages.length);
            System.out.println(inbox.getUnreadMessageCount() + "封未读邮件!");
            System.out.println(inbox.getNewMessageCount() + "封新邮件!");
            System.out.println("你好,即将遍历消息内容!");
            for (Message m : messages){
                if (m.getFlags().contains(Flags.Flag.SEEN)){
                    continue;
                }
                System.out.println("发现一封未读邮件即将分析!");
      /*          IMAPMessage ms = (IMAPMessage) m;
                System.out.println("11");
                String subject = MimeUtility.decodeText(ms.getSubject());
                System.out.println("22");*/
                bean = new Bean();
                mailReceiver(m);
                list.add(bean);
       //         m.setFlag(Flags.Flag.SEEN, true);
                System.out.println("————-————————————————————————————");
            }

        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            msg = "0";
        } finally{
            try {
                inbox.close(false);
                store.close();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }finally{
                return msg;
            }
        }
    }

    private void mailReceiver(Message msg)throws Exception{
        // 发件人信息
        System.out.println("分析邮件内容");
        System.out.println("获取发件人地址");
        Address[] froms = msg.getFrom();
        if(froms != null) {
            System.out.println("即将打印发件人地址。。。");
            InternetAddress addr = (InternetAddress)froms[0];
            System.out.println("发件人地址:" + addr.getAddress());
            bean.setPersonAddress(addr.getAddress());
            bean.setPersonName(addr.getPersonal());
            System.out.println("发件人显示名:" + addr.getPersonal());
        }
        System.out.println("邮件主题:" + msg.getSubject());
        bean.setTheme(msg.getSubject());
        // getContent() 是获取包裹内容, Part相当于外包装
        System.out.println("即将分析邮件内容。。。");
        Object o = msg.getContent();
        if(o instanceof Multipart) {
            System.out.println("Multipart");
            Multipart multipart = (Multipart) o ;
            reMultipart(multipart);
        } else if (o instanceof Part){
            System.out.println("Part");
            Part part = (Part) o;
            rePart(part);
        } else {
            System.out.println("既不是Multipart也不是Part");
            System.out.println("类型" + msg.getContentType());
            System.out.println("内容" + msg.getContent());
        }
    }
    /**
     * @param part 解析内容
     * @throws Exception
     */
    private void rePart(Part part) throws MessagingException, IOException{
        System.out.println("进入rePart");
            if(part.getContentType().startsWith("TEXT/PLAIN")) {
                System.out.println("HTML内容:" + part.getContent());
                bean.setUrl((String) part.getContent());
            } else {
                //System.out.println("HTML内容:" + part.getContent());
            }
    }

    /**
     * @param multipart // 接卸包裹(含所有邮件内容(包裹+正文+附件))
     * @throws Exception
     */
    private void reMultipart(Multipart multipart) throws Exception {
        System.out.println("邮件共有" + multipart.getCount() + "部分组成");
        System.out.println("即将一次处理各部分");
        // 依次处理各个部分
        for (int j = 0, n = multipart.getCount(); j < n; j++) {
            System.out.println("处理第" + j + "部分");
            Part part = multipart.getBodyPart(j);//解包, 取出 MultiPart的各个部分, 每部分可能是邮件内容,
            // 也可能是另一个小包裹(MultipPart)
            // 判断此包裹内容是不是一个小包裹, 一般这一部分是 正文 Content-Type: multipart/alternative
            if (part.getContent() instanceof Multipart) {
                System.out.println("此部分仍有小包裹,将迭代处理!");
                Multipart p = (Multipart) part.getContent();// 转成小包裹
                //递归迭代
                reMultipart(p);
            } else {
                rePart(part);
            }
        }
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:19864次
    • 积分:542
    • 等级:
    • 排名:千里之外
    • 原创:76篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类