Thursday, 27 September 2012

JAVA Program to send an e-mail


SAMPLE JAVA PROGRAM TO SEND AN EMAIL

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.io.InputStream;
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()
     .getResourceAsStream("mail.properties");
      properties.load(inputStream);
    } 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(
  (String)properties.get("mail.login.username"), 
  (String)properties.get("mail.login.password"));
      }
    });

    // 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.setFrom(fromAddress);
    msg.setSubject(subject);
    msg.setRecipient(RecipientType.TO, toAddress);
    msg.setContent(body, "text/plain");

    // Finally send  the  email
    Transport.send(msg);

    // 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 mail.properties.
# 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. 

mail.smtp.host=smtp.gmail.com
mail.smtp.auth=true

mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false

# This is your login name and password not required. Instead of 
# hardcoding them in program, I have added here.
mail.login.username=abc@xyz.com
mail.login.password=*****


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

0 comments:

Post a Comment