我需要使用java发送图像作为电子邮件正文的一部分: -
我遵循的步骤如下
拍摄图像并使用org.apache.commons.codec.binary.Base64对其进行编码,并在html中将其用作图像src标记。
解码编码图像并使用邮件程序API发送。
我面临的问题是,某些图片正在通过邮件程序API传递并在电子邮件正文中可见,而某些图片则没有。
图像的大小是否会产生问题?
谢谢&问候 Kundan Saini
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
答案 0 :(得分:1)
所以你试图在邮件正文中发送base64图像。问题可能与某些邮件代理不支持这一事实有关。
您可以在此处查看:Send a base64 image in HTML email
基本上,在邮件正文中发送图像的更好方法是使用cid和图像作为附件(也无法在任何地方使用)。
有一篇很好的文章描述了向邮件添加图片的不同方式及其优缺点: https://sendgrid.com/blog/embedding-images-emails-facts/