如何获取电子邮件所有附件的文件名? [英] How to get filename of all attachements of email?
问题描述
我正在尝试使用java和imap获取所有电子邮件附件的文件名。我的代码是:
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);
但即使电子邮件包含附件,它也会始终打印出来。我在SO上看到了不同的代码但没有如果附件不止一个,我不知道该怎么办。
PS:我只想获取文件名而不想下载附件。
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.
推荐答案
首先,使用以下代码确定邮件是否包含附件:
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());
这篇关于如何获取电子邮件所有附件的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!