Monday, October 14, 2013

How to send an email using Java API & Gmail account


Below blog explains about sending an email using Gmail email address as from email and Java API

Below is the sample code snippet to send email using Java Mail API.

Download the Java Mail Jar and set in class path
Here is the link to download java-mail.jar  http://www.oracle.com/technetwork/java/index-138643.html

       
import com.sun.mail.util.MailSSLSocketFactory;

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;

import java.net.URL;

import java.security.GeneralSecurityException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import javax.mail.Session;
    /**
   * De limit the toEmail List
   * Authenticate
   * @param msg
   * @param subject
   * @param toEmail
   * @param fromEmail
   * @return
   * @throws Exception
   */
  public static String sendEmail(String msg, String subject, String toEmail, String fromEmail)
    throws Exception
  {
    String toEmails[] = toEmail.split(",");
    System.out.println("TO:::FROM:::SUBJ:::BODY:::" + toEmail + "-" + fromEmail + "-" + subject + "-" + msg);

    Session session = setSessionAuthentication();
    InternetAddress from = new InternetAddress(fromEmail);
    InternetAddress to[] = new InternetAddress[toEmails.length];
    for (int c = 0; c < toEmails.length; c++)
    {
      to[c] = new InternetAddress(toEmails[c]);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.addRecipients(Message.RecipientType.TO, to);
    message.setSubject(subject);
    message.setText(msg);
    Transport.send(message);
    // msg="OK Msg Posted Successfully";
    return "EMail Sent Successfully";
  }

  /**
   *
   * @return
   * @throws Exception
   */
  public static Session setSessionAuthentication()
    throws Exception
  {
    final String username = "FM@gmail.com";
    final String password = "GMAIL PASSWORD";
    //Using SSL
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    // USING TLS
    //        Properties props = new Properties();
    //        props.put("mail.smtp.auth", "true");
    //        props.put("mail.smtp.starttls.enable", "true");
    //        props.put("mail.smtp.host", "smtp.gmail.com");
    //        props.put("mail.smtp.port", "587");
    props.put("mail.debug", "true");
    MailSSLSocketFactory sf = null;
    try
    {
      sf = new MailSSLSocketFactory();
    }
    catch (GeneralSecurityException e1)
    {
      e1.printStackTrace();
    }
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.socketFactory", sf);
    Session session = Session.getInstance(props, new javax.mail.Authenticator()
      {
        protected PasswordAuthentication getPasswordAuthentication()
        {
          return new PasswordAuthentication(username, password);
        }
      });
    return session;
  }
       
 

No comments:

Post a Comment