我是java邮件的新手。我想发一封带有图片附件的邮件。我已经尝试使用以下代码将图像附加到邮件中。
BodyPart messageBodyPart = new MimeBodyPart();
if (content == null) {
messageBodyPart.setText("");
} else {
messageBodyPart.setText(content);
}
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
// messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(
attachedFile2.getBytes("UTF-8"),
"application/octet-stream");
//attachedFile2 is the filename of image.
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachedFile2);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);这段代码工作正常。接收的带有图像附件的邮件。但问题是图像以不支持的格式显示或不显示原始图像。
我不知道如何解决这个问题。
请帮帮我..
提前谢谢..
发布于 2012-09-18 18:15:18
您可以尝试这样做:
private void addImageResource(final MimeMultipart content, final String resourceName,
final String resourceTitle) throws MessagingException, IOException {
MimeBodyPart msgBodyPart = new MimeBodyPart();
URL imgURL = getClass().getClassLoader().getResource(resourceName);
final DataSource dsImg = new FileDataSource(imgURL.getFile());
msgBodyPart.setDataHandler(new DataHandler(dsImg));
msgBodyPart.setHeader("Content-ID", resourceTitle);
content.addBodyPart(msgBodyPart);
}https://stackoverflow.com/questions/12474462
复制相似问题