Removing attachment from MimeMessage

3k views Asked by At

I am reading eml file from local disk:

InputStream is = new FileInputStream(body_path);
MimeMessage message = new MimeMessage(session,is);
Multipart multipart = (Multipart)message.getContent();

Now how do i remove attachment of ".dat" type?

1

There are 1 answers

1
Caadi0 On

You can do something like this :-

Compose a new mimemsg and add all parts one by one except the part with extension DAT

Compose a new message :-

MimeMessage newMimeMsg;
MimeMultipart content;

if (mimemsg.isMimeType("multipart/*")) {
     Multipart multipartmsg = (Multipart) mimemsg.getContent();

for (int i = 0; i < multipartmsg.getCount(); ++i) {
MimeBodyPart bodypart = (MimeBodyPart) multipartmsg.getBodyPart(i);
if(getFileExtension(bodypart.getFileName()).equalsIgnoreCase("dat") {
    // Do Nothing
} else {
    content.addBodyPart(bodypart);
}
}
newMimeMsg.setContent(content);
} else {
   newMimeMsg = mimemsg;
}

public static String getFileExtension(String docFileName) {
        String[] tokens = docFileName.split("\\.(?=[^\\.]+$)");
        return tokens[1];
    }