如何使用JavaMail API解析Mbox文件?

时间:2013-11-06 15:50:33

标签: java parsing javamail java-api mbox

我想使用JavaMail解析.mbox文件就像这个http://mail-archives.apache.org/mod_mbox/lucene-java-user/201210.mbox一样。

我想做的是:

Session session = Session.getDefaultInstance(new Properties());
Store store = session.getStore("Here should go the .mbox file");
store.connect();

Folder folder = store.getFolder(server);
folder.open(Folder.READ_ONLY);
...

哪个证明是错的。任何建议都会有所帮助。

提前谢谢你。

更新:工作示例

public class MBoxFileReader implements MessageReader {
    private final Path path;  // Path to .mbox file

    public MBoxFileReader(Path path) {
        this.path = path;
    }

    @Override
    public Message[] readMessages() {
        Message[] messages = new Message[0];
        URLName server = new URLName("mbox:" + path.toString());
        Properties props = new Properties();
        props.setProperty("mail.mime.address.strict", "false");
        Session session = Session.getDefaultInstance(props);
        try {
            Folder folder = session.getFolder(server);
            folder.open(Folder.READ_ONLY);
            messages = folder.getMessages();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用JavaMail mbox Store,但您需要自己构建它。

答案 1 :(得分:1)

这可以通过Apache Mime4j完成:

    CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder();
    final File mbox = new File(mboxPath);

    for (CharBufferWrapper message : MboxIterator.fromFile(mbox).charset(ENCODER.charset()).build()) {
        System.out.println(message);
    }

你需要:

<dependencies>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.james</groupId>
        <artifactId>apache-mime4j</artifactId>
        <version>0.8.1</version>
        <type>pom</type>
    </dependency>

</dependencies>