Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename of all attachements of email?

I am trying to get the filename of all the attachements of emails using java and imap.My code is:

MimeMessage msg = (MimeMessage) messages[i];
String fileName = msg.getFileName();
System.out.println("The file name of this attachment is " + fileName);

but it prints null always even if email contain attachment..I have seen different codes on SO but none worked...and I don't know what to do if attachment is more than one .
PS:I only want to get the filename and don't want to download attachments.

like image 593
cooljohny Avatar asked May 27 '14 06:05

cooljohny


People also ask

Can you search attachment names in Outlook?

Find attachments using Outlook's search box If you want to search a specific folder, select that folder in the folder pane. At the top of the message list, you'll see a box that says Search Current Mailbox. Click to place your cursor in that box, type hasattachments:yes, and then click Enter.

What is the name of attachment?

An attachment friendly name is usually equal to its FilenameOriginal, but it may be different sometimes. To obtain the original filename of the attached file, use FilenameOriginal property. Since Name value can be empty, it's usually more convenient to use Filename value instead. This sample loads the message from .


2 Answers

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

like image 96
fluminis Avatar answered Sep 20 '22 13:09

fluminis


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);
}
like image 31
l0wacska Avatar answered Sep 20 '22 13:09

l0wacska