I need to send an image as part of email body using java :-
The Steps I followed is as below
Take an image and encode it using org.apache.commons.codec.binary.Base64 and use it in html as image src tag.
Decode the encoded image and send using the mailer API.
The Issue I have facing that some image is passing through the mailer API and visible in email body and some are not.
Is it the size of image which is creating the issue ?
Thanks & Regards 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 Files as below :-
<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