Is it possible to get only the count of attachments for a mail in Java? I tried using this:
DataHandler handler = message.getDataHandler();
AttachedFileName= handler.getName();
This lists out all the attachments for all mails inbox but not for specific mails.
Is this possible if so how?
Thanks!
Receiving email with attachment in Java As we receive the email, we can receive the attachment also by using Multipart and BodyPart classes found in JavaMail API. For better understanding of this example, learn the steps of sending email using JavaMail API first.
A message may contain one or several attachments. As discussed in the article Send e-mail with attachment in Java, if a message contains attachments, its content must be of type MultiPart, and the part contains a file must be of type MimeBodyPart. So it’s important to determine if a message may contain attachments using the following code:
The body must be of type Multipart for containing attachments. The Multipart object holds multiple parts in which each part is represented as a type of BodyPart whose subclass, MimeBodyPart – can take a file as its content. The steps to create a multipart message with multiple parts are as follows:
The content with attachments is a BodyPart called MultiPart. If an email has any attachments, it has a disposition equal to “ Part.ATTACHMENT “. In case there are no attachments, the disposition is null. The getDisposition method from the Part interface gets us the disposition.
This should give you the attachment count,
Multipart multipart = (Multipart) message.getContent();
int attachmentCount = multipart.getCount();
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