Pierre
Pierre

Reputation: 35296

Parsing the messages in my local mail file using java

I'd like to parse and filter the messages in my local inbox (e.g: thunderbird) using java. Something like:

 java MyProgram <  ~/.thunderbird/xxxxx.default/Mail/yyyyy/Inbox > statistics.txt

As far as I can see there is the jakarta mail api and its implementation ( org.eclipse.angus ) but all the examples I see are using a remote inbox, using

import javax.mail.Session;
import javax.mail.Store;

so is there an API (in jakarta mail ?) that could parse such local flat files and let me iterate over all the messages. Something like:

ParserSomething localbox  = ParserSomething.of(System.in);
Iterator<Message> iter = localbox.iterator();
while(iter.hasNext()) {
  Message msg = iter.next();
  System.err.println(msg.getTitle());
  for(Attachment a : msg.getAttachements()) {
      try(InputStream in = a.getInputStream() ) {
        (...)
       }
   } 
}

Upvotes: 0

Views: 54

Answers (1)

Pierre
Pierre

Reputation: 35296

ok I got the answer here.

Using org.apache.james.mime4j

import org.apache.james.mime4j.parser.*;
import org.apache.james.mime4j.stream.*;
import org.apache.james.mime4j.*;
public class ScanMail extends AbstractContentHandler {

@Override
public void field(Field field) throws MimeException {
    System.out.println(field);
    }

public static void main(String[] args) {
    try {
        final ContentHandler handler = new ScanMail();
        final  MimeConfig config = MimeConfig.DEFAULT;
        final MimeStreamParser parser = new MimeStreamParser(config);
        parser.setContentHandler(handler);
        parser.parse(System.in);
        }
    catch(Throwable err) {
        err.printStackTrace();
        }
    }
};

compilation:

wget -O work/apache-mime4j-core-0.8.11.jar  "https://repo1.maven.org/maven2/org/apache/james/apache-mime4j-core/0.8.11/apache-mime4j-core-0.8.11.jar"
wget -O work/commons-io-2.18.0.jar  "https://repo1.maven.org/maven2/commons-io/commons-io/2.18.0/commons-io-2.18.0.jar"
javac -d work -cp work/apache-mime4j-core-0.8.11.jar ScanMail.java
echo | java -cp work:work/apache-mime4j-core-0.8.11.jar:work/commons-io-2.18.0.jar ScanMail

Upvotes: 0

Related Questions