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

No comments: