How to get filename of all attachements of email?

左心房为你撑大大i 提交于 2020-01-13 12:13:10

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/23882797/how-to-get-filename-of-all-attachements-of-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!