Search code examples
javaemailjakarta-mail

Checking for attachments using javamail without getting the message content


I have tried to find some kind of answer or even a hint on how to do this, but, with no luck.

I want to check if email message has any attachments. But if I use suggested code:

Object content = bPart.getContent();

if (content instanceof String) {
    if (Part.ATTACHMENT.equalsIgnoreCase(bPart.getDisposition()) || StringUtils.isNotBlank(bPart.getFileName())) {
        // It's attachment
        haveAttachment = true;
    }
    else {
        // It's text or html
        emailBody = content.toString();
    }
}
else if (content instanceof InputStream) {
    if (Part.ATTACHMENT.equalsIgnoreCase(bPart.getDisposition()) || StringUtils.isNotBlank(bPart.getFileName())) {
        // It's attachment
        haveAttachment = true;
    }
}

I must use getContent() function on my email message and message is automatically marked as SEEN (read) on the server.

Can anybody help me how to write a simple function to get basic email message info and display if message has any attachments without having to get the whole message content? Actually, I need help with attachments only, because I already know how to get other basic header fields and they do not request getContent() method and they do not mark my email as SEEN.

How does a regular email client does this? I guess there must be some fast and simple way to check if email has attachments.

Thank you in advance!

Edit: Alternatively, is there a way to use getContent() function without marking email as SEEN?


Solution

  • I don't know where you got that "suggested" code but it certainly wasn't from the JavaMail web site.

    You'll want to read this JavaMail FAQ entry.

    To check the MIME type of a part, use the isMimeType method. You can find an example in the msgshow.java sample program.