Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email attachment parsing via mime4j

Tags:

java

mime

smtp

perl

I am using a small java smtp library (http://code.google.com/p/subethasmtp/), by this I need to parse the incoming emails in separate components viz body, attachments etc.

I am trying to use mime4j , but the documentation suggests that mime4j can only give event notification or token notification and nothing else. For stripping out body and attachments etc I had to use my own custom logic inside the event handlers. Is my observation correct?

If yes then how can I use mime4j to use for my requirement. Please suggest.

I badly need an approach that takes in the smtp data stream and returns me with an array of attachment references or streams in fully parsed out form in java. Please help.

Thanks in advance

Ashish Sharma

like image 222
Ashish Sharma Avatar asked Apr 20 '10 14:04

Ashish Sharma


2 Answers

Mime4j can definitely do what you need. Make a subclass of org.apache.james.mime4j.message.SimpleContentHandler, and implement the bodyDecoded method. Then pass this subclass into a MimeStreamParser instance. You'll see that bodyDecoded is called once per body or attachment, and the stream it gives you contains the data with Base64 or Quoted-Printable decoding already performed.

If you don't like event-based APIs in general, you can try the more DOM-like functionality exposed via the org.apache.james.mime4j.message.Message class. You can call Message.getBody() and then see if what it gives you back is an instance of Multipart, TextBody, BinaryBody, etc. If Multipart, then you can call Multipart.getBodyParts to recurse into the subparts.

like image 77
Joe Cheng Avatar answered Oct 02 '22 08:10

Joe Cheng


@Ashish the other option since you are using SubEthaSmtp is to do what SubEtha Mail List manager does: http://code.google.com/p/subetha/source/browse/trunk/src/org/subethamail/common/SubEthaMessage.java

The linked class extends SMTPMessage and which has a bunch of getPart() methods. javax.mail.Part has most of what you need to turn an attachment into a file.

like image 28
Adam Gent Avatar answered Oct 02 '22 08:10

Adam Gent