[在嵌入式Javax.mail中发送字符串时,数据源图像损坏

问题描述 投票:0回答:1

我正在尝试通过java通过邮件发送inline imag e。我有byte array,所以我使用以下功能将字节数组转换为string

 public static String getImgString(byte[] fileImg) throws IOException {
    String imageString = new String(fileImg,"UTF-8");
    return imageString;
}

我有一个字符串,我通过转换器验证了这个字符串,它显示并使用了我的图像。

现在,我使用以下代码将图像附加到邮件正文中。

byte[] arr = getImageFileBytes(); // I got byte[] from this function
DataSource dataSourceImage = new ByteArrayDataSource(getImgString(arr),"image/png"");

MimeBodyPart imageBodyPart = new MimeBodyPart();
imageBodyPart.setDataHandler(new DataHandler(dataSourceImage));

我收到如下电子邮件。

我认为DataSource转换中缺少某些格式,或者我需要添加其他格式data:image / png; base64到图像字符串?

为了获得String中的图像,我需要做哪些更改。

提前感谢。

enter image description here

java javamail
1个回答
1
投票

如果图像数据实际上在文件中,则应使用attachFile方法:

MimeBodyPart mbp = new MimeBodyPart();
mbp.attachFile("file.png", "image/png", "base64");

如果仅在内存中存储图像数据,则需要执行以下操作:

MimeBodyPart mbp = new MimeBodyPart();
ByteArrayDataSource bds = new ByteArrayDataSource(getImageFileBytes(), "image/png");
mbp.setContent(new DataHandler(bds));

当然,如果要从单独的html部分引用此图像,则需要确保两者都包装在multipart /相关部分中。

更多信息在JavaMail FAQ中。

© www.soinside.com 2019 - 2024. All rights reserved.