Friday 18 March 2016

Java Send mail via gmail

In this post, I am going to explain how to send mail programmatically.

Login to your gmail and go to following link and Turn on secure apps.


Following utility class send mail. Update the variables senderMailId, password, receiverMailId in MailUtil class.

import java.util.Properties;

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;

public class MailUtil {

 private static final String senderMailId = "";
 private static final String password = "";
 private static String receiverMailId = "";
 private static Properties props = new Properties();

 static {
  loadProperties();
 }

 private static void loadProperties() {
  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");
 }

 public static boolean sendEmail(final String to, final String subject,
   final String body) {

  Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(senderMailId, password);
     }
    });

  try {

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(senderMailId));
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse(to));
   message.setSubject(subject);
   message.setText(body);

   Transport.send(message);

   System.out.println("Message send to " + to);
   return true;

  }

  catch (MessagingException e) {
   System.out.println("Email sending failed " + e.getMessage());
   return false;
  }
 }

 public static boolean isValidEmailAddress(String email) {
  String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
  java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
  java.util.regex.Matcher m = p.matcher(email);
  return m.matches();
 }

 public static void main(String args[]) {
  sendEmail(receiverMailId, "Hello", "Have a good day PTR");
 }
}



No comments:

Post a Comment