Java MimeMessage to eml File with all attachments

Viewed 3347

I have an incoming MimeMessage in my JAMES mail server. I want to create an eml file dumping the message completely. I tried using the writeTo method of MimeMessage - resulting file contains only the text body of the email. The attachments are not written to the eml file. My code is something like

String logFileName = "dumpNow.eml";
incomingEmail.getMessage().writeTo(new FileOutputStream(new File(logFileName)));

I do not get any multipart content in the dump. Is there any Util available to do this? Apache Mimeutils is also giving the same result.

1 Answers

Try this :

// Create your attachement file
File emlFile = new File("myFile.eml");
emlFile.createNewFile();
incomingEmail.getMessage().writeTo(new FileOutputStream(emlFile));

MimeBodyPart attachment = new MimeBodyPart();

DataSource source = new FileDataSource(emlFile);

attachment.setDataHandler(new DataHandler(source));
attachment.setHeader("Content-Type", "application/octet-stream");
attachment.setFileName("myFileName.eml");
attachment.setDescription("My file description");
attachment.setDisposition(Part.ATTACHMENT);

multipart.addBodyPart(attachmentFile);

I think it is because you missed to set the header and the disposition in your code.

Hope it helps,

Related