gpt4 book ai didi

java - 如何将邮件中的base64图像附加到JavaMail和MimeMessageHelper?

转载 作者:行者123 更新时间:2023-12-02 01:53:28 24 4
gpt4 key购买 nike

我正在尝试发送带有图像附件的 Mime 电子邮件,但我知道如何执行此操作。我尝试了网上的解决方案,但没有成功。我将获得编码的图像,需要解码并附加在邮件中。这是我的代码

public class SendEmail{

public static void main( String[] args ) throws javax.mail.MessagingException, IOException
{

String value= "Wyk+HjAxHTAyNzg3MDUdODQwHTAxOR0wMDAwMDAwMDAwMDAwMDAd" +
"RkRFQh0wMDAwMDAwHTA0MB0dMS8xHTUwLjVMQh1OHVcgMzR0aCBTdHJlZXQdQ" +
"XVzdGluHVRYHSAeMDYdMTBaR0QwMDQdMTFaUmVjaXBpZW50IENvbXBhbnkgTmFt" +
"ZR0xMlo5MDEyNjM3OTA2HTE0WioqVEVTVCBMQUJFTCAtIERPIE5PVCBTSElQKio" +
"dMjNaTh0yMlocWR0yMFogHDAdMjZaNjEzMxwdHgQ=";

JavaMailSender mailSender = getJavaMailSender();

MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper;
Map<String,Object> map = new HashMap<>();

try{
helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
String sendTo = "abc@gmail.com";
String htmlMsg = "<h1> hello </h1>";

mimeMessage.setContent(htmlMsg, "text/html");

// add attachment encode in base64
byte[] decodedImg Base64.decodeBase64(value);
// dont know how to attache the decode img


helper.setTo(sendTo);
helper.setSubject("Subject");
mailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}



}

最佳答案

尝试:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(value.getBytes()));

但是请阅读:从代码来看,您似乎已经对图像进行了编码。“值”似乎是 Base64 格式。您不应该处理它,因为它已经为您完成了。

// you can attach a file directly to the helper
FileSystemResource file = new FileSystemResource(new File("image_file.jpg"));
helper.addAttachment("MyImageName.jpg", file);

如果附件不是您磁盘上的文件,您可以使用:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(IOUtils.toByteArray(attachment)));

如果这是一个输入流或者这个:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(value.getBytes()));

关于java - 如何将邮件中的base64图像附加到JavaMail和MimeMessageHelper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52645322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com