我正在使用下一个代码使用 javamail API 从我的邮箱帐户下载附件和正文,它工作得很好。但是,当电子邮件中有内嵌或嵌入的图像时,图像既不会作为文本文件也不会作为附件下载。我是 Java 新手,一直在网上阅读,但没有找到易于理解的实施解决方案。任何解决方法或代码来完成它?
这是我正在使用的代码:
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println(content);
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) {
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Text = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)) {
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
InputStream inStream = bodyPart.getInputStream();
FileOutputStream outStream = new FileOutputStream(new File(
downloadDirectory + fileName));
byte[] tempBuffer = new byte[4096];// 4 KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
inStream.close();
outStream.close();
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
如果它是内联图像,我尝试添加下一个 if 语句以显示消息,但不走运:
public void procesMultiPart(Multipart content) {
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
// NOT WORKING
if (o instanceof Image) {
System.out.println("procesMultiPart has Inline Images");
}
//
else if (o instanceof String) {
System.out.println("Text = " + o);
} else if (null != bodyPart.getDisposition()
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)) {
String fileName = bodyPart.getFileName();
System.out.println("fileName = " + fileName);
InputStream inStream = bodyPart.getInputStream();
FileOutputStream outStream = new FileOutputStream(new File(
downloadDirectory + fileName));
byte[] tempBuffer = new byte[4096];// 4 KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
inStream.close();
outStream.close();
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}