Friday, June 7, 2013

Java Mail Client with GMAIL SMTP and PURE SMTP

This post shows you small example of java mail client with gmail smtp and pure smtp server.

 package ia.demo.utils;  
 import ia.demo.exception.fault.EmptyRecipientException;  
 import java.util.Properties;  
 import javax.mail.AuthenticationFailedException;  
 import javax.mail.Authenticator;  
 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;  
 /**  
  * Mail sending class  
  *  
  * @author Erdenebayar  
  */  
 public class MailUtil {  
  /* GMAIL SMTP CONFIGURATION */  
  static String GMAIL_HOST = "smtp.gmail.com";  
  static String GMAIL_FROM = "yourmail@gmail.com";  
  static String GMAIL_PASS = "yourpass";  
  static String GMAIL_PORT = "587";  
  
/* PURE SMTP CONFIGURATION */  
  static final String SMTP_HOST_NAME = "mail.server.com";  
  static final String SMTP_AUTH_USER = "yourmail@server.com";  
  static final String SMTP_FROM_ADDRESS = "yourmail@server.com";  
  static final String SMTP_AUTH_PWD = "yourpass";  
 
public static void main(String[] aaa) throws MessagingException {  
   String emailMsgTxt = "Message from Java";  
   final String emailSubjectTxt = "You are receiving mail from Java system";  
   String[] to = {"recipient1@yahoo.com", "recipient2@outlook.com"};  
   sendMailWithGmail(to, emailMsgTxt, emailSubjectTxt);  
   sendMailWithSmtp(to, emailMsgTxt, emailSubjectTxt);  
  }

  /**  
   * Email configured with GMAIL SMTP server  
   *  
   * @param recipients - List of recipients mail address  
   * @param subjectText - Subject of mail  
   * @param bodyText - Body of mail  
   * @throws MessagingException  
   */
public static void sendMailWithGmail(String[] recipients, String subjectText, String bodyText) throws MessagingException {  
   if (recipients.length > 0) {  
    Properties props = System.getProperties();  
    props.put("mail.smtp.starttls.enable", "true"); // added this line  
    props.put("mail.smtp.host", GMAIL_HOST);  
    props.put("mail.smtp.user", GMAIL_FROM);  
    props.put("mail.smtp.password", GMAIL_PASS);  
    props.put("mail.smtp.port", GMAIL_PORT);  
    props.put("mail.smtp.auth", "true");  
    Session session = Session.getDefaultInstance(props, null);  
    MimeMessage message = new MimeMessage(session);  
    message.setFrom(new InternetAddress(GMAIL_FROM));  
    InternetAddress[] toAddress = new InternetAddress[recipients.length];  
    // To get the array of addresses  
    for (int i = 0; i < recipients.length; i++) { // changed from a while loop  
     toAddress[i] = new InternetAddress(recipients[i]);  
    }  
    System.out.println(Message.RecipientType.TO);  
    for (int i = 0; i < toAddress.length; i++) { // changed from a while loop  
     message.addRecipient(Message.RecipientType.TO, toAddress[i]);  
    }  
    message.setSubject(subjectText);  
    message.setText(bodyText);  
    Transport transport = session.getTransport("smtp");  
    transport.connect(GMAIL_HOST, GMAIL_FROM, GMAIL_PASS);  
    transport.sendMessage(message, message.getAllRecipients());  
    transport.close();  
   } else {  
    throw new EmptyRecipientException("There are no recipient");  
   }  
  }

  /**  
   * Email configured with PURE SMTP server  
   *  
   * @param recipients - List of recipients mail address  
   * @param subjectText - Subject of mail  
   * @param bodyText - Body of mail  
   * @throws MessagingException  
   * @throws AuthenticationFailedException  
   */  
  public static void sendMailWithSmtp(String recipients[], String subjectText, String bodyText) throws MessagingException, AuthenticationFailedException {  
   if (recipients.length > 0) {  
    boolean debug = false;  
    //Set the host smtp address  
    Properties props = new Properties();  
    props.put("mail.smtp.host", SMTP_HOST_NAME);  
    props.put("mail.smtp.auth", "true");  
    Authenticator auth = new SMTPAuthenticator();  
    Session session = Session.getDefaultInstance(props, auth);  
    session.setDebug(debug);  
    // create a message  
    Message msg = new MimeMessage(session);  
    // set the from and to address  
    InternetAddress addressFrom = new InternetAddress(SMTP_FROM_ADDRESS);  
    msg.setFrom(addressFrom);  
    InternetAddress[] addressTo = new InternetAddress[recipients.length];  
    for (int i = 0; i < recipients.length; i++) {  
     addressTo[i] = new InternetAddress(recipients[i]);  
    }  
    msg.setRecipients(Message.RecipientType.TO, addressTo);  
    // Setting the Subject and Content Type  
    msg.setSubject(subjectText);  
    msg.setContent(bodyText, "text/plain");  
    Transport.send(msg);  
   } else {  
    throw new EmptyRecipientException("There are no recipient");  
   }  
  }  
  private static class SMTPAuthenticator extends javax.mail.Authenticator {  
   @Override  
   public PasswordAuthentication getPasswordAuthentication() {  
    String username = SMTP_AUTH_USER;  
    String password = SMTP_AUTH_PWD;  
    return new PasswordAuthentication(username, password);  
   }  
  }  
 }  

Thank you,
Erdenebayar

Linkedin: http://www.linkedin.com/in/erdenebayare
Twitter: http://twitter.com/#!/erdenebayare