Sunday, October 30, 2011

How to send Email through Java


How to send email using java mail api...

Following class will describes how to send email through java


import java.io.IOException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

/**
 * @created by velmurugan pousel
 * @created on Oct 17, 2011
 * @project TestBatch
 */
public class TestEmailUtil {

 private final static Logger logger = Logger.getLogger(TestJobLauncher.class);

 private static  Properties emailProps ;

 /**
  * method to load the email host/port information and construct the email properties to
  * get the session to send mail
  * @throws TestException
  */
 public void init() throws TestException {

  logger.info(" loading the email host information");
  try {
   if (emailProps == null) {
    emailProps = new Properties();
    Properties prop =  new Properties();
    prop.load(getClass().getClassLoader().getResourceAsStream(ExtractULC.Test_EMAIL_CONFIG_FILE_NAME));
    
     //mail.host=Smtp.test.com
    //mail.port=25
    //mail.auth=false
    //mail.auth.userid=
    //mail.auth.password=
    //mail.from=
    //mail.cc=dl-test-Tech_Suport
    emailProps.put("mail.smtp.host", prop.get(ExtractULC.EMAIL_HOST_NAME));
    emailProps.put("mail.smtp.port", prop.get(ExtractULC.EMAIL_HOST_PORT));
    emailProps.put("mail.smtp.auth", prop.get(ExtractULC.EMAIL_AUTH_LEVEL));
    emailProps.put("mail.from", prop.get(ExtractULC.EMAIL_FROM_ADDRESS));
    emailProps.put("mail.cc", prop.get(ExtractULC.EMAIL_CC_ADDRESS));
   } 
  } catch (IOException e) {
   logger.error(" Error during email information loading.."+ e.getMessage());
   throw new TestException(e);
  }
 }
 /**
  * util method to send the email notification
  * @param recipients
  * @param subject
  * @param message
  * @param from
  * @throws MessagingException
  * @throws TestException
  */
 public void postMail(String recipients[], String subject, String message,
   String from) throws MessagingException, TestException {
  logger.info(" entering into the postmail method.....");
  boolean debug = false;
  try {
   init();
   // create some properties and get the default Session
   Session session = Session.getDefaultInstance(emailProps, null);
   session.setDebug(debug);
   // create a message
   Message msg = new MimeMessage(session);
   
   // set the from and to address
   InternetAddress addressFrom = new InternetAddress(emailProps.getProperty(ExtractULC.EMAIL_FROM_ADDRESS));
   msg.setFrom(addressFrom);
     
   // set the cc address incase if its error message
   if (from != null && from.trim().length() > 0){  
    InternetAddress addressCC = new InternetAddress(emailProps.getProperty(ExtractULC.EMAIL_CC_ADDRESS));
    msg.setFrom(addressCC);
   }
      
   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);
   msg.addHeader("TestHeader", "Test header");
   // Setting the Subject and Content Type
   msg.setSubject(subject);
   msg.setContent(message, "text/plain");
   Transport.send(msg);
   logger.info(" email successfully send...");
  } catch (Throwable e) {
   logger.error(" Error during email send....");
      throw new TestException(e);
  }
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(List<String> emailIds, String sub, String body, String to)
   throws TestException {
  try {
   //postMail(Collections., sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String emailId, String sub, String body)
   throws TestException {
  try {
   postMail(new String[] { emailId }, sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String emailId, String sub, String body, boolean addCC)
   throws TestException {
  try {
   postMail(new String[] { emailId }, sub, body, "cc");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
  
 /**
  * method to send the email notification into the internal vendors
  *
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String[] emailIds, String sub, String body, boolean addCC)
   throws TestException {
  try {
   postMail(emailIds , sub, body, "cc");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 }
      
 /**
  * method to send the email notification into the internal vendors
  * @param emailIds
  * @param sub - subject to send
  * @param body
  * @return
  * @throws TestException
  */
 public boolean sendMail(String[] emailIds, String sub, String body)
  throws TestException {
  try {
   postMail(emailIds, sub, body, "");
  } catch (Throwable e) {
   throw new TestException(e);
  }
  return false;
 } 

 public static void main(String[] args) {
  try {
   String[] mailIds = new String[]{"vels007@gmailcom"};
   new TestEmailUtil().postMail(mailIds, "Test", " Test message", "");
  } catch (Throwable e){
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment