Search code examples
javaimapattachment

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.


Solution

  • 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