Send HTML email in Java using URL as the content body

With the help of the Apache commons HttpClient we make a request to the given URL and then read the response data to insert that into the body of the email. The HTML email is done using the HtmlEmail class also available in the Apache commons library. This Java example uses gmail as its SMTP server but you can change that to anything of your choice, also the following jars are needed in the project classpath
  • commons-email-1.2.jar
  • commons-logging-1.1.1.jar
  • httpclient-4.1.1.jar
  • httpcore-4.1.jar
  • mail.jar
package com.as400samplecode;


import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class SendHTMLEmail {

 public static void main(String[] args) {

  try {

   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost("");
   HttpResponse response = httpclient.execute(httpPost);
   HttpEntity resEntity = response.getEntity();

   String responseBody = "";
   if (resEntity != null) {
    responseBody = EntityUtils.toString(resEntity);

   HtmlEmail htmlEmail = new HtmlEmail();
   htmlEmail.setAuthenticator(new DefaultAuthenticator("userId", "password"));
   htmlEmail.addTo("", "recipient");
   htmlEmail.setFrom("", "sender");
   htmlEmail.setSubject("Send HTML email with body content from URI");

  } catch (EmailException e) {
  } catch (ParseException e) {
  } catch (IOException e) {



No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.