gpt4 book ai didi

java - 使用 javax.mail 在邮件正文中发送编码图像

转载 作者:行者123 更新时间:2023-11-30 06:26:37 26 4
gpt4 key购买 nike

我需要使用 java 发送图像作为电子邮件正文的一部分:-

我遵循的步骤如下

  • 获取图像并使用 org.apache.commons.codec.binary.Base64 对其进行编码,然后在 html 中将其用作图像 src 标记。

  • 解码编码图像并使用邮件程序 API 发送。

我面临的问题是,某些图像正在通过邮件程序 API 传递并在电子邮件正文中可见,而有些图像则不可见。

是图像的大小造成了问题吗?

感谢和问候昆丹赛尼

public static void main(String[] args) {

String htmlContent = readFile("c:\\temp\\imagenotsending.html");


String encodeHtmlContent = encodeStringToBase64(htmlContent);
System.out.println(encodeHtmlContent);

String decodeHtmlBody = decodeStringToBase64(encodeHtmlContent);
sendMailNew(decodeHtmlBody);
}

public static void sendMailNew(String body) {
String to = "to address";

// Sender's email ID needs to be mentioned
String from = "from address here";

// Assuming you are sending email from localhost
String host = "host here";

// Get system properties
Properties properties = System.getProperties();

// Setup mail server
properties.setProperty("host", host);

// Get the default Session object.
Session session = Session.getDefaultInstance(properties);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);

message.setContent(body, "text/html; charset=utf-8");

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));

// Set Subject: header field
message.setSubject("This is the Subject Line!");

// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}


public static String encodeStringToBase64(String aString) {
byte[] encodedBytes = Base64.encodeBase64(aString.getBytes());
return new String(encodedBytes);
}

public static String decodeStringToBase64(String aString) {
byte[] decodedBytes = Base64.decodeBase64(aString.getBytes());
return new String(decodedBytes);
}

Html 文件如下:-

<html>

<head>
<title>Test</title>
</head>

<body>

<img src="data:image/png;base64,iVBORw0KGg.......rkJggg==">


</body>

</html>

Base 64 encoding of image below not sending Base 64 encoding of image below is sending

最佳答案

所以您正在尝试在邮件正文中发送 Base64 图像。问题可能与某些邮件代理不支持这一事实有关。

您可以在这里看到:Send a base64 image in HTML email

所以基本上在邮件正文中发送图像的更好方法是使用 cid 和图像作为附件(也不是在任何地方都有效)。

有一篇很好的文章描述了向邮件添加图像的不同方法及其优缺点: https://sendgrid.com/blog/embedding-images-emails-facts/

关于java - 使用 javax.mail 在邮件正文中发送编码图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47076846/

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