Skip to content

Send html email with embedded image

import com.sun.deploy.net.HttpResponse;
import org.apache.commons.mail.HtmlEmail;
import sun.net.www.http.HttpClient;
import javax.imageio.ImageIO;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.net.ssl.*;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;

import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Properties;

/**
* Created by liyang4 on 11/08/2016.
*/
public class RandomTest {
public static void main(String[] args) {
System.out.println(“Hello World!”); // Display the string.
try {

HtmlEmail emailOut = new HtmlEmail();

File file = new File(“downloaded.jpg”);
file.deleteOnExit();

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance(“SSL”);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
URL url = new URL(“http://www.mkyong.com/image/mypic.jpg”);

// BufferedImage img = ImageIO.read(url);
org.apache.commons.io.FileUtils.copyURLToFile(url, file);
String cid = emailOut.embed(file, “abc”);

// set the html message
emailOut.setHtmlMsg(“<html>The logo – <img src=\”cid:”+cid+”\”></html>”);

emailOut.setHostName(“[A smtp server]”);
emailOut.setSmtpPort(25);

ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>();
emailRecipients.add(new InternetAddress(“[A email address]”));
emailOut.setTo(emailRecipients);
emailOut.setFrom(“[A email address]”);
emailOut.setSubject(“Test image”);

emailOut.send();
} catch (Exception e) {
e.printStackTrace();
}
}

static void disableHostNameVerification(SSLEngine engine)
{
SSLParameters sslParameters = engine.getSSLParameters();
{
// by default, it’s set to “HTTPS”, and the server certificate must match the request host.
// disable it for this example, since the server certificate is ill constructed.
sslParameters.setEndpointIdentificationAlgorithm(null);
}
engine.setSSLParameters(sslParameters);
}
}

%d bloggers like this: