How do I remove an attachment from a MimeMessage? If I use getContent().getParent().removeBodyPart(BodyPart part) is seems to work, but when I write the MimeMessage to harddisk with writeTo(OutputStream) the attachments are still in the textfile. What am I doing wrong?

Dieter Wimberger

You start with a reference to a MimeMessage. Then you get its content, which will be a reference to a MimeMultipart instance. Next you get its parent again, which leaves you with the reference to the MimeMessage you started from. I wonder why there is no MessagingException thrown if you try to remove a MimeBodyPart that is part of the MimeMultipart instance, but at least it should return false (which tells you it did not work out).
Here is a piece of code that should do the job:

//suppose you have a reference to a MimeMessage
//called myMessage

MimeMultipart mmp=(MimeMultipart)myMessage.getContent();

//now a loop over its body parts
for(int i=0; i<getCount(); i++) {
    MimeBodyPart mbp=(MimeBodyPart)mmp.getBodyPart(i);
    if(hasToBeRemoved(mbp)) {
        //this will shift all parts down so:
        //the index of the loop needs correction

//if you want to persist that new state
//Note: only works if the folder is opened READ_WRITE !


    private boolean hasToBeRemoved(MimeBodyPart mbp) {

	//check according to your criteria
	//and return true or false