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

Wednesday, March 16, 2016

A Bug with Microsoft Outlook - Showing unread mail in Taskbar

As the email system is configured in different systems like Laptop mobile etc...
Once you read the mail from any one of the device it should be updated on all the devices automatically.

In Outlook it does that, but never removes the notification from the desktop, I feel it is a disturbing thing in desktops, and push you to check what is the new mail is...

To remove this icon the only option in the outlook is close the outlook and reopen it.


Here I have read the mail from mobile, In the list of mails and the inbox is cleared, but it is showing new mail icon in the TaskBar.


Monday, September 14, 2015

NodeMCU - Avoid the system hanging from infinite loop and run TCP Server after getting IP

I was trying to develop my NodeMCU as a controller for Home Automation,
Once I found searching for wifi in loop ended in an infinite loop and hence I have to FLASH the firmware, and reload it. To avoid the same in future I did teh following

The best solution i found is create a delay of some seconds before starting the infinite loop, so that when system has to be reset, you will enough time to do it.

Some tutorials is here : http://www.esp8266.com/viewtopic.php?f=18&t=1705

From the above link Setting wifi delay is done as follows.

--Startup file It is trying to connect my mobile Wifi--
SSID =   "AndroidAP"
PWD  =    "csnv6345"
HTTPServerFile = "ServerFile.lua"
    wifi.setmode(wifi.STATION)
    wifi.sta.config(SSID, PWD)
    print("Wait 5 seconds please")
    tmr.alarm(1, 5000, 1, function() -- Infinite Loop for keep checking the wifi status in a 5s delay.
        if(wifi.sta.status() ==5) then  -- Once the IP is set, stoping the timer and executing the file.
            tmr.stop(1)
            dofile(HTTPServerFile)
        end
    end)
print("End of startup")

A Sample Server file, which on the LED on first request and off on next. to test the Wifi Connection

lighton=0
pin=0
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        print(payload)
         if lighton==0 then
            lighton=1
            gpio.write(pin,gpio.HIGH)
        else
            lighton=0
             gpio.write(pin,gpio.LOW)
        end
    end)
end)



Sunday, September 6, 2015

How to customise code Autocompletion in ace editor.

It is easy to customize the code completion in the ace editor,
The following code will do the autosuggestion in the editor.

 editor = ace.edit("editor")
  editor.setOptions({
    // mode: "ace/mode/javascript",
    enableBasicAutocompletion: true
  });
  editor.completers.push({
    getCompletions: function(editor, session, pos, prefix, callback) {
      callback(null, [
        {value: "foo", score: 1000, meta: "custom"},
        {value: "bar", score: 1000, meta: "custom"}
      ]);
    }
  })
But the above code will do autosuggestion with the completion we have provided with the words available in the editor, 
This code is done in the ace/ext/language_tools.js

You can customize the TextCompleter in the file language_tools.js 
In line no 70 if you remove the textCompletor, you can complete control according to your recommendation.
example
 var completers = [snippetCompleter,  keyWordCompleter];//textCompleter


Tuesday, August 18, 2015

First Adruino program worked. fixed "adruino due is not listed in board list"

It is an Amazing experience with Adruino DUE,
I faced the issue of not finding Adruino DUE in board list,
Just used teh following link, which solved the issue
http://blog.startingelectronics.com/cant-find-arduino-due-in-board-list-of-ide

Thanks www.blog.startingelectronics.com

Publishing my Embedded Experiements @ http://facebook.com/EmbeddedClubQatar

Thursday, May 14, 2015

A Collection Framework in Java Script

Hi,
I just created a Collection framework in javascript.

please find the code in https://github.com/askeralim/Collection.js


Asker Ali M