`
i2534
  • 浏览: 180111 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

javamail收取信件

    博客分类:
  • util
阅读更多
主要是为了解决某些邮件客户端发送邮件时把繁体也编码为gb2312,导致乱码出现.
懒得存数据库了,就写文件了.
另没有解决multipart中只取text/html或者text/plain的问题.
长时间潜水,第一次在je发表东西,自己纪念下.
package com.hcycom.lan.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
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.Message.RecipientType;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.ParseException;

import com.sun.mail.pop3.POP3Folder;

public class ShowMail {

    private static final String D_MAIL = "D:/mail/";
    private static final String BR = "\n";

    public static String replaceGB2312ToGBK(String source) {
        if (source == null) {
            return null;
        }
        if (source.toLowerCase().indexOf("?gb2312?") != -1) {
            source = source.replaceAll("\\?[gG][bB]2312\\?", "?gbk?");
        }

        return source;

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new ShowMail().show();

    }

    private void show() {
        Properties prop = System.getProperties();
        Session session = Session.getDefaultInstance(prop);

        try {
            Store store = session.getStore("pop3");
            store.addStoreListener(new StoreListener() {

                public void notification(StoreEvent e) {
                    switch (e.getMessageType()) {
                    case StoreEvent.ALERT:
                        System.out.println("alert : " + e.getMessage());
                        break;
                    case StoreEvent.NOTICE:
                        System.out.println("notice : " + e.getMessage());
                        break;
                    }

                }

            });
            store.connect("pop.163.com", "i2534", "password");
            if (store.isConnected()) {
                POP3Folder inbox = (POP3Folder) store.getFolder("INBOX");
                if (inbox.exists()) {
                    inbox.open(Folder.READ_ONLY);
                    File dir = new File(D_MAIL);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File uids = new File(dir, "uids");
                    HashSet set = new HashSet();
                    HashSet newUids = new HashSet();
                    if (uids.exists()) {
                        BufferedReader br = new BufferedReader(new FileReader(
                                uids));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            set.add(line);
                        }
                        br.close();
                    }
                    int nCount = inbox.getMessageCount();
                    System.out.println("Inbox contains " + nCount
                            + " messages.");
                    for (int i = 1; i <= nCount; i++) {
                        System.out.println("now accept " + i);
                        MimeMessage msg = (MimeMessage) inbox.getMessage(i);

                        String uid = inbox.getUID(msg);
                        if (set.contains(uid)) {
                            System.out
                                    .println("this message is already exists.skip to next.");
                            continue;
                        }

                        File mail = File.createTempFile(new SimpleDateFormat(
                                "yyyyMMdd_").format(new Date()), ".mail", dir);
                        FileWriter fw = new FileWriter(mail, true);

                        newUids.add(uid);
                        fw.write("UID : " + uid);
                        fw.write(BR);

                        String subject = msg.getHeader("Subject", null);
                        fw
                                .write("Subject : "
                                        + MimeUtility
                                                .decodeText(replaceGB2312ToGBK(subject)));
                        fw.write(BR);

                        fw.write("Send Date : "
                                + new SimpleDateFormat("yyyy-MM-dd HH:mm")
                                        .format(msg.getSentDate()));
                        fw.write(BR);

                        fw.write("From : ");
                        dumpAddresses(msg.getFrom(), fw);
                        fw.write(BR);

                        fw.write("To : ");
                        dumpAddresses(msg.getRecipients(RecipientType.TO), fw);
                        fw.write(BR);

                        fw.write("CC : ");
                        dumpAddresses(msg.getRecipients(RecipientType.CC), fw);
                        fw.write(BR);

                        fw.write("Content type : " + msg.getContentType());
                        fw.write(BR);

                        parts(msg, fw);

                        fw.flush();
                        fw.close();

                        System.out.println("accept over.");
                    }

                    if (!newUids.isEmpty()) {
                        FileWriter fw = new FileWriter(uids, true);
                        for (String s : newUids) {
                            fw.write(s);
                            fw.write(BR);
                        }
                        fw.flush();
                        fw.close();
                    }
                }

                inbox.close(false);

            }

            store.close();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void dumpAddresses(Address[] addresses, FileWriter fw)
            throws UnsupportedEncodingException, IOException {
        if (addresses == null || fw == null) {
            return;
        }
        for (Address address : addresses) {
            fw.write(MimeUtility.decodeText(replaceGB2312ToGBK(address
                    .toString())));
            fw.write(";");
        }
    }

    private static void parts(Part part, FileWriter fw) {
        if (part == null || fw == null) {
            return;
        }
        try {
            Object content = part.getContent();
            if (content instanceof Multipart) {
                MimeMultipart mmp = (MimeMultipart) content;
                for (int index = 0; index < mmp.getCount(); index++) {
                    parts(mmp.getBodyPart(index), fw);
                }
            } else if (content instanceof InputStream) {
                MimeBodyPart mbp = (MimeBodyPart) part;
                String contentType = mbp.getContentType();
                String name = getFileName(contentType);
                fw.write("File name : " + name);
                String cid = null;
                if ((cid = mbp.getContentID()) != null) {
                    fw.write(" (cid : " + cid + ")");
                }
                String disposition = null;
                if ((disposition = mbp.getDisposition()) != null) {
                    fw.write(" (disposition : " + disposition + ")");
                }
                fw.write(BR);
                File file = new File(D_MAIL + name);
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = (InputStream) content;
                int i = -1;
                while ((i = is.read()) != -1) {
                    fos.write(i);
                }
                fos.flush();
                fos.close();
            } else if (content instanceof String) {
                fw.write("----------- part begin -------------");
                fw.write(BR);
                if (part instanceof BodyPart) {
                    MimeBodyPart mbp = (MimeBodyPart) part;
                    String contentType = mbp.getContentType();
                    String language = getCharset(contentType);

                    String encoding = mbp.getEncoding();

                    fw.write("Content type : " + contentType);
                    fw.write(BR);
                    if (encoding != null) {
                        fw.write("Encoding : " + encoding);
                        fw.write(BR);
                    }

                    if (mbp.getRawInputStream() != null && encoding != null) {
                        InputStream is = MimeUtility.decode(mbp
                                .getRawInputStream(), encoding);
                        InputStreamReader isr = new InputStreamReader(is,
                                language);
                        BufferedReader br = new BufferedReader(isr);
                        String line = null;
                        StringBuilder sb = new StringBuilder();
                        while ((line = br.readLine()) != null) {
                            sb.append(line).append(BR);
                        }
                        fw.write(sb.toString());
                        fw.write(BR);
                    }
                } else {
                    fw.write((String) content);
                    fw.write(BR);
                }
                fw.write("----------- part end -------------");
                fw.write(BR);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getCharset(String contentType) {
        String language = null;
        try {
            ContentType ct = new ContentType(contentType);
            language = ct.getParameter("charset");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (language == null) {
            language = MimeUtility.getDefaultJavaCharset();
        }
        if (language.equalsIgnoreCase("gb2312")) {
            language = "gbk";
        }
        return language;
    }

    private static String getFileName(String contentType) {
        String name = null;
        try {
            ContentType ct = new ContentType(contentType);
            name = ct.getParameter("name");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        if (name == null) {
            name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        }
        try {
            name = MimeUtility.decodeText(replaceGB2312ToGBK(name));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return name;
    }
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics