Thursday, 27 September 2012

JAVA Program to send an e-mail


The JavaMail API is not part of core Java SE, but an optional extension. In addition, it is required in Java Enterprise Edition. The JavaMail packages can be accessed in two ways:
  • by placing j2ee.jar in the classpath
  • or, by placing both mail.jar and activation.jar in the classpath
The javax.mail API uses a properties file for reading server names and related configuration. These settings will override any system defaults. Alternatively, the configuration can be set directly in code, using the JavaMail API.
In below example, I am sending mail using JavaMail API with GMail SMTP on Port 465.
package  com.mail.tutorial;

import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
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.MimeMessage.RecipientType;

public class SendEmail {
  private  static Properties properties = null;

  static {
    // Load  the  properties file
    try  {
      properties = new Properties();
      InputStream  inputStream  = SendEmail.class.getClassLoader()
    } catch  (Exception e) {
      // Catching  the  exception as null condition  
   // is handled in the methods.

  public static void sendTextMail(String to, String from,  String subject,  
  String body) throws  Exception {

    if (properties.isEmpty()) {
      throw new Exception("Cannot  send mail. Host  data not available.");

    // Authenticate  the  session  with username and password
    Session  session  = Session.getInstance(properties, new Authenticator(){
      protected PasswordAuthentication getPasswordAuthentication()
        return new PasswordAuthentication(

    // Create to and from addresses
    InternetAddress  fromAddress  = new InternetAddress(from);
    InternetAddress  toAddress =  new  InternetAddress(to);

    // Create the message instance 
 // and add the sender, recipient, subject and body.
    Message  msg  = new MimeMessage(session);
    msg.setRecipient(RecipientType.TO, toAddress);
    msg.setContent(body, "text/plain");

    // Finally send  the  email

    // Now,  the  mail would have  reached  the  recipients.  
 // Ask  them to  check their  inbox.
Also you need to set the below properties in a properties file called
# Configuration file for javax.mail 
# If a value for an item is not provided, then 
# system defaults will be used. These items can 
# also be set in code.


# This is your login name and password not required. Instead of 
# hardcoding them in program, I have added here.

You need to download below jars to run the above example 
1. j2ee.jar 
1. mail.jar and activation.jar