How to get filename of all attachements of email?

First, to determine if a message may contain attachments using the following code:

// suppose 'message' is an object of type Message
String contentType = message.getContentType();

if (contentType.contains("multipart")) {
    // this message may contain attachment
}

Then we must iterate through each part in the multipart to identify which part contains the attachment, as follows:

Multipart multiPart = (Multipart) message.getContent();

for (int i = 0; i < multiPart.getCount(); i++) {
    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        // this part is attachment
        // code to save attachment...
    }
}

And to save the file, you could do:

part.saveFile("D:/Attachment/" + part.getFileName());

Source


there is an easier way with apache commons mail:

final MimeMessageParser mimeParser = new MimeMessageParser(mimeMessage).parse();
final List<DataSource> attachmentList = mimeParser.getAttachmentList();
for (DataSource dataSource: attachmentList) {
            final String fileName = dataSource.getName();
            System.out.println("filename: " + fileName);
}