Tuesday, May 17, 2016

How to send Email using GMail with Java Mail API

I just finished with sending Email using Java Mail by connecting the Gmail SMTP.

package org.core.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.AddressException;

public class SendEmailUsingGMailSMTP {
 public static void main(String[] args) throws AddressException, MessagingException {
  Properties mailServerProperties;
  Session getMailSession;
  MimeMessage generateMailMessage;
  mailServerProperties = System.getProperties();
  mailServerProperties.put("mail.smtp.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  mailServerProperties.put("mail.smtp.auth", "true");
  mailServerProperties.put("mail.smtp.starttls.enable", "true");
  System.out.println("Mail Server Properties have been setup successfully..");
 
  getMailSession = Session.getDefaultInstance(mailServerProperties, null);
  generateMailMessage = new MimeMessage(getMailSession);
  generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
  generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("cc@gmail.com"));
  generateMailMessage.setSubject("Test Mail from Java Mail");
  String emailBody = "Test email by Java Mail JavaMail API example. " + "\n Regards, \nAdmin";
  generateMailMessage.setContent(emailBody, "text/html");
  System.out.println("Mail Session has been created successfully..");
 

  Transport transport = getMailSession.getTransport("smtp");
 
  transport.connect("smtp.gmail.com", "mail@gmail.com", "password");
  transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
  transport.close();
 }
}

Please ensure the Gmail account is NOT using Gmail 2 Step Verification, and allow less secure apps to have access,

Because Java Mail works here as a Less secure App.
You can do it using following Link

https://www.google.com/settings/security/lesssecureapps


If we want to sent the HTML content Email with an attachment, try the following
package org.core.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class SendEmailUsingGMailSMTP {
 public static void main(String[] args) throws AddressException, MessagingException, IOException {
  String emailAddress = "fromemail@gmail.com";
  String emailBody = "Test email by Java Mail using JavaMail API example. "
    + "\n Regards, \n Asker";
  //call readFile to read the HTML template file and send it through email, and attach the the image from the resourse we have. 
  //emailBody = readFile()
  sendEmail(emailAddress, emailBody);
 }

 public static void sendEmail(String emailAddress, String emailBody) throws AddressException, MessagingException, IOException {

  // Step1
  System.out.println("\n 1st ===> setup Mail Server Properties..");
  Properties mailServerProperties;
  Session mailSession;
  MimeMessage mailMessage;
  mailServerProperties = System.getProperties();
  mailServerProperties.put("mail.smtp.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  mailServerProperties.put("mail.smtp.auth", "true");
  mailServerProperties.put("mail.smtp.starttls.enable", "true");
  System.out.println("Mail Server Properties have been setup successfully..");

  // Step2
  System.out.println("\n\n 2nd ===> get Mail Session..");
  mailSession = Session.getDefaultInstance(mailServerProperties, null);
  mailMessage = new MimeMessage(mailSession);
  mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
  mailMessage.setSubject("Greetings from Asker..");
  System.out.println("Mail Session has been created successfully..");
  
  MimeBodyPart messageBodyPart1 = new MimeBodyPart();
  messageBodyPart1.setHeader("Content-Type", "text/html");
  DataSource dataSourceHtml= new ByteArrayDataSource(emailBody, "text/html");
  messageBodyPart1.setDataHandler(new DataHandler(dataSourceHtml));

  // 4) create new MimeBodyPart object and set DataHandler object to
  // this object
  MimeBodyPart messageBodyPart2 = new MimeBodyPart();
  
  URL url=SendEmailUsingGMailSMTP.class.getResource("lesssecure.jpg");
  DataSource source = new FileDataSource(url.getFile());
  messageBodyPart2.setDataHandler(new DataHandler(source));
  messageBodyPart2.setFileName("My Image.jpg");

  // 5) create Multipart object and add MimeBodyPart objects to this
  // object
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart1);
  multipart.addBodyPart(messageBodyPart2);
  
  mailMessage.setContent(multipart);

  // Step3
  System.out.println("\n\n 3rd ===> Get Session and Send mail");
  Transport transport = mailSession.getTransport("smtp");

  // Enter your correct gmail UserID and Password
  // if you have 2FA enabled then provide App Specific Password
  transport.connect("smtp.gmail.com", "email@gmail.com", "password");
  transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
  transport.close();
 }
  private static String readFile( ) throws IOException, URISyntaxException {
      BufferedReader reader = new BufferedReader( new FileReader (new File(SendEmail.class.getResource("template.html").toURI())));
      String         line = null;
      StringBuilder  stringBuilder = new StringBuilder();
      String         ls = System.getProperty("line.separator");

      try {
          while( ( line = reader.readLine() ) != null ) {
              stringBuilder.append( line );
              stringBuilder.append( ls );
          }
          return stringBuilder.toString();
      } finally {
          reader.close();
      }
  }
}


Askerali Maruthullathil

Sunday, May 15, 2016

How to email the charts generated by google charts or any image.

I had a requirement to send the charts generated by Google Charts to the user email address.
I found the solution as follows.

If we render the image using SVG, i couldnt found an option to send the image, But base64 data can be sent using ajax and the server can save it.

Steps
1.       Render the Chart as follows. It will render image in Base64 format.
      // Wait for the chart to finish drawing before calling the getImageURI() method.
      google.visualization.events.addListener(chart, 'ready', function () {
        chart_div.innerHTML = '<_ _="" id="chartIMG" img="" src="' + chart.getImageURI() + '">';
        console.log(chart_div.innerHTML);
      });
A google provided example here 
2.       Now the chart_div.innerHTML will have the Base64 image,
3.       Send the Base 64 Image to the server on button click or any action.
4.       Create a Servlet to handle the request with Base64 Image data.
5.       Convert the Base64 Image data to a PNG image using the following code.
Base64.Decoder decoder = Base64.getDecoder();
      byte[] imgBytes = decoder.decode(value);
      FileOutputStream osf = new FileOutputStream(new File("MyChart,png"));
      osf.write(imgBytes);
      osf.flush();
6.       Using Java SMTP server send an email with HTML template, add this image link to the email as html email template designed.
7.       Send the email, I used hMailServer to send it, but you can integrate any existing mail server

Some references on How Embedd image in email and its short comings as follows.

  1. Base64 Image sending Issue : https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
  2. Embedding technique : https://sendgrid.com/blog/embedding-images-emails-facts/


Regards
Asker