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.
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.
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 .
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);
}
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