我正在使用以下Java
代码尝试提取电子邮件附件:
private static List<File> extractAttachment(Message message) {
List<File> attachments = new ArrayList<File>();
try {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
System.out.println("bodyPart.getDisposition(): " + bodyPart.getDisposition());
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
InputStream is = bodyPart.getInputStream();
String filePath = "/tmp/" + bodyPart.getFileName();
System.out.println("Saving: " + filePath);
File f = new File(filePath);
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
attachments.add(f);
}
} catch (IOException | MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return attachments;
}
但是,我总是得到bodyPart.getDisposition(): null
. 任何线索我应该如何提取内联附件?
谢谢
PS:我Apple Mail
在 Mac 上使用客户端发送带有附件的测试电子邮件。然而电子邮件客户端不应该被关注。
我明白了,确实我必须进行一些“递归”并检查嵌套内容并检查Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition()
.
以下是代码,认为对某人有用:
private static List<File> extractAttachment(Multipart multipart) {
List<File> attachments = new ArrayList<File>();
try {
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getContent() instanceof Multipart) {
// part-within-a-part, do some recursion...
extractAttachment((Multipart) bodyPart.getContent());
}
System.out.println("bodyPart.getDisposition(): " + bodyPart.getDisposition());
if (!Part.INLINE.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
InputStream is = bodyPart.getInputStream();
String filePath = "/tmp/" + bodyPart.getFileName();
System.out.println("Saving: " + filePath);
File f = new File(filePath);
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
attachments.add(f);
}
} catch (IOException | MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return attachments;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句