Thursday 15 August 2013

How to send email using Java and Gmail smtp server?

Send verification link to email or send an email for verification.

Sending an email from your java code is quite simple. If you need to send multiple emails or email for multiple users (cc/bcc) the best and simplest way is to use the already available java mail api for the purpose.

The javax.mail jar contains many classes that deals with various aspects of emailing, the MIME helps you configure properties of the email content, the BodyPart enables content to be send in body, the Message covers over all content and etc.

Now, before starting you should know about SMTP.

An SMTP stands for Simple Mail Transfer Protocol that establishes and configure the mail server, for our example we will be using easily available Gmail SMTP server. Before you start sending emails you need to configure your SMTP server and set properties according to our requirements.

Also, check if the SMTP port on your system is open and available, the common port for SMTP server is 25. In case it is blocked by admin you may configure it using one of the good resources freely available on internet - Mercury

All setup, let's get started:

//System properties
Properties props = new Properties(); 

// Setup our mail server
props.put("mail.smtp.host", SMTP_HOST); 

props.put("mail.smtp.user",FROM_NAME);

props.put("mail.smtp.ssl.enable", "true");

props.put("mail.smtp.port", "25");

props.put("mail.debug", "true");

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.starttls.enable","true");

props.put("mail.smtp.EnableSSL.enable","true");

props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  

props.setProperty("mail.smtp.socketFactory.fallback", "false");  

props.setProperty("mail.smtp.port", "465");  

props.setProperty("mail.smtp.socketFactory.port", "465");

Now, SMTP_HOST  is gmail, FROM_ADDRESS is the sender's email address, TO_ADDRESS is the receiver's email and so configure all of them in our private variables:

private String SMTP_HOST = "smtp.gmail.com"; 

private String FROM_ADDRESS = "youremail@gmail.com"; 

private String FROM_PASSWORD = "yourgmailpassword";

private String TO_ADDRESS = "anotheremail@gmail.com";

private String FROM_NAME = "CodeHunk Email Verification"; 

private String SERVER_URL= "http://localhost:8080/EmailServer/EmailServlet?"; 

You see that we are using our own localhost server where we will want the user to be redirected once he clicks the verification link received in his email.

Next, setup our Message and MIME.

//Session object.

Session session = Session.getInstance(props, new AuthorizeEmail()); 

//PasswordAuthentication validates the user at first

class AuthorizeEmail extends Authenticator { 
   @Override 
   protected PasswordAuthentication getPasswordAuthentication() { 
      return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD); 
   } 
}

try{

  // Get the default Mime object.
  MimeMessage message = new MimeMessage(session);//if only text
  // Set our FromAddress.
  message.setFrom(new InternetAddress(FROM_ADDRESS));
  // Set our ToAddress.
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
  // Set our subject for the mail.
  message.setSubject("CodeHunk Email Verification Test");
}


If you wish to send email to many people you can add "Message.RecipientType.CC" or "Message.RecipientType.BCC" in your addRecipient field.

The next thing is to set the message string, you can use html in your string and that's perfectly legal and fine.

// Now set the actual message
String verificationID= "verificationID=100";
String htmlMessageContent = "<h3 align='center'>In order to proceed with CodeHunk registration click the link.</h3> <br> <h4 align = 'center' \"background-color:cyan\">Verification link: <a href = \""+SERVER_URL+verificationID+"\">Click to verify your email</a></h4>";



The verificationID will ensure only the receiver clicked the link

//for the moment we comment out below line
//message.setText(htmlMessageContent, "text/html");
//set "text/plain" if you don't need html in your message



If you need to send images also in your email you can also do that:
Let's take this image for our email:
// Create the message part for SENDING IMAGE
//This HTML mail have to 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");

// first part  (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H3 ><font color=\"red\" face=\"Comic sans MS\" size=\"2\">Hello CodeHunk Visitor!</font></H3><center><img src=\"cid:image\"></center><br>" + htmlMessageContent;
messageBodyPart.setContent(htmlText, "text/html");


It is important to give your image an id like cid:image


// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDisposition(MimeBodyPart.INLINE);// show image with msg content
DataSource dataSource = new FileDataSource("D:\\hello.jpg");
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setHeader("Content-ID","<image>");

// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);


//finally send our email:
 Transport.send(message);


Finally, let's put everything together at one place.

The SendEmail Class:

package com.codehunk.email;

import java.util.HashMap;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



/**
 * 
 * @author Atif Imran 2013
 * @blog codehunk.blogspot.in
 * @website www.strizen.com
 *
 */

public class SendEmail {
 private String SMTP_HOST = "smtp.gmail.com";  
 private String FROM_ADDRESS = "youremail@gmail.com";  
 private String FROM_PASSWORD = "yourpassword";
 private String TO_ADDRESS = "anotheremail@gmail.com";  
 private String FROM_NAME = "CodeHunk Email Verification";  
 private String SERVER_URL = "http://localhost:8080/EmailServer/EmailServlet?";  


 //PasswordAuthentication validates the user at first
 class AuthorizeEmail extends Authenticator {  
  @Override  
  protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD);  
  }  
 }

 public static void main(String[] args){
  SendEmail se = new SendEmail();
  se.sendEmail();
 }

 public void sendEmail(){
  //verify a user before registering

  // System properties
  Properties props = new Properties();  

  // Setup our mail server
  props.put("mail.smtp.host", SMTP_HOST);  
  props.put("mail.smtp.user",FROM_NAME); 
  props.put("mail.smtp.ssl.enable", "true"); 
  props.put("mail.smtp.port", "25"); 
  props.put("mail.debug", "true"); 
  props.put("mail.smtp.auth", "true"); 
  props.put("mail.smtp.starttls.enable","true"); 
  props.put("mail.smtp.EnableSSL.enable","true");
  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");   
  props.setProperty("mail.smtp.socketFactory.fallback", "false");   
  props.setProperty("mail.smtp.port", "465");   
  props.setProperty("mail.smtp.socketFactory.port", "465"); 



  // Session object.
  Session session = Session.getInstance(props, new AuthorizeEmail());  

  try{
   // Get the default Mime object.
   MimeMessage message = new MimeMessage(session);//if only text
   // Set our FromAddress.
   message.setFrom(new InternetAddress(FROM_ADDRESS));
   // Set our ToAddress.
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
   // Set our subject for the mail.
   message.setSubject("CodeHunk Email Verification Test");


   // Now set the actual message
   String verificationID= "verificationID=100";
   String htmlMessageContent = "

In order to proceed with CodeHunk registration click the link.

Verification link: Click to verify your email

"; //for the moment we comment out below line //message.setText(htmlMessageContent, "text/html"); //set "text/plain" if you don't need html in your message // Create the message part for SENDING IMAGE // This HTML mail have to 2 part, the BODY and the embedded image MimeMultipart multipart = new MimeMultipart("related"); // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello CodeHunk Visitor!

" + htmlMessageContent; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); // second part (the image) messageBodyPart = new MimeBodyPart(); messageBodyPart.setDisposition(MimeBodyPart.INLINE);// show image with msg content DataSource dataSource = new FileDataSource("D:\\hello.jpg"); messageBodyPart.setDataHandler(new DataHandler(dataSource)); messageBodyPart.setHeader("Content-ID",""); // add it multipart.addBodyPart(messageBodyPart); // put everything together message.setContent(multipart); // Send message Transport.send(message); }catch (MessagingException mex) { System.out.println("MessagingException: "+mex.getMessage()); mex.printStackTrace(); } } }
The EmailServlet:

package com.codehunk.email;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EmailServlet
 */
public class EmailServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmailServlet() {
        super();
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //check if the parameter contains verificationID
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  if(request.getParameter("verificationID")!=null && request.getParameter("verificationID").equals("100")){
   out.write(""+
     "Success"+
     "

Email successfully verified!

"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

The Result:




When verification link is clicked:




That's all. I hope you've enjoyed it. Cheers ;)
Read more »

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Web Hosting