users@javamail.java.net

Re: removing attachments from locally stored message

From: Bill Shannon <bill.shannon_at_oracle.com>
Date: Mon, 29 Apr 2013 11:52:40 -0700

xoot123_at_yahoo.it wrote on 04/29/13 11:33:
> Hello,
> My application offers the possibility to save emails from IMAP accounts to a
> local database.
> Later on, the user can remove the attachments from those saved messages, with
> two options:
> a) remove the original message;
> b) keep the original message.
>
> The whole original message is saved locally, meaning that an OutputStream is
> used to write the message (writeTo()) to it and from that an InputStream is
> obtained that populates a BLOB column.
>
> The problem is, in case (b) I can only create a MimeMessage from the saved
> stream, with new MimeMessage(null, myInputStream).
> The new message is passed to a method that removes all its attachments.
> I saw that when removing the attachments (and precisely when saveChanges() is
> called) all the MimeMessage internal stream references are nullified, so that a
> call to getSize() returns -1.
>
> Since I need to store the message size on the database, along with other
> informations, the only solutions I found to make JavaMail give me that is to
> create a new MimeMessage from the attachments-removed MimeMessage.
>
> So, to sum it up: <database column> -> msg = new MimeMessage(null, myIS) ->
> removeAttachments(msg) -> newMsg = new MimeMessage(null, msg).
>
> Are all those steps necessary or is there a more efficient way to do this?

It would be very complicated to keep track of the final size of a message
after each of those "edits" to the message, so JavaMail doesn't even try.

The technique you're using is implemented by "serializing" the entire message
to a MIME byte stream, then deserializing the message to create a new
MimeMessage object. If all you want is the size, a more efficient approach
is to serialize the message (using writeTo) to an OutpuStream that does
nothing with the data but counts how much data is written. After writeTo
is done, ask the stream how much data was written.