首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中上传带有邮件的图片附件?

如何在java中上传带有邮件的图片附件?
EN

Stack Overflow用户
提问于 2012-09-18 17:48:14
回答 1查看 394关注 0票数 2

我是java邮件的新手。我想发一封带有图片附件的邮件。我已经尝试使用以下代码将图像附加到邮件中。

代码语言:javascript
复制
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);

这段代码工作正常。接收的带有图像附件的邮件。但问题是图像以不支持的格式显示或不显示原始图像。

我不知道如何解决这个问题。

请帮帮我..

提前谢谢..

EN

回答 1

Stack Overflow用户

发布于 2012-09-18 18:15:18

您可以尝试这样做:

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12474462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档