I'm looking for the best way to save an email body which includes inline images and HTML content. I want to Retain everything the mail contains.
My ultimate Goal is to save the complete email body into a PDF
If there is a direct way to write email body into PDF ?
if not what would be the best format to save the email ?
I can convert HTML, DOC etc to PDF using some other available API.
private void downloadAttachment(Part part, String folderPath) throws Exception {
String disPosition = part.getDisposition();
String fileName = part.getFileName();
String decodedText = null;
logger.info("Disposition type :: " + disPosition);
logger.info("Attached File Name :: " + fileName);
if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
logger.info("DisPosition is ATTACHMENT type.");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName != null && disPosition == null) {
logger.info("DisPosition is Null type but file name is valid. Possibly inline attchment");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName == null && disPosition == null) {
logger.info("DisPosition is Null type but file name is null. It is email body.");
File file = new File(folderPath + File.separator + "mail.html");
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
}
}
protected int saveEmailAttachment(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = null;
InputStream is = null;
int ret = 0, count = 0;
try {
bos = new BufferedOutputStream(new FileOutputStream(saveFile));
part.writeTo(new FileOutputStream(saveFile));
} finally {
try {
if (bos != null) {
bos.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
logger.error("Error while closing the stream.", ioe);
}
}
return count;
}
Please suggest. Thank you!
Save it in its natural state, as a MimeMessage.
JavaMail MimeMessages can be streamed to text, since that's how they arrive in mail. For example, MimeMessage.writeTo saves the message out as text. Similarly, MimeMessage.parse reads it back in. One in a MimeMessage, you can get the text, the attachments, etc. quite easily.
You could also stream it out as a serialized Java object, but, frankly, I wouldn't. The text representation is much more useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With