Friday, December 2, 2011

Java Mail Send Code

Java Mail Send Code
------------------------
This class usefull to send email. (modify this class according to your requirement)

/**
* @author paria
*/
/****************************************************************************
* FILE: PARIAEmail.java
* DESC: Simple e-mail class.
* Rev Date Name Comment
****************************************************************************/

package com.emc.email;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.BodyPart;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.flexnet.league.integration.bizo.PTCUpdateService;
import com.flexnet.league.integration.common.exception.PARIAException;
import com.flexnet.league.integration.common.util.ResponseStatus;

/** Simple use case for the javax.mail API. */

public class PARIAEmail {

          /** Logger **/
          private static final Logger logger = Logger.getLogger(PTCUpdateService.class);


         /** _CLASS_VERSION **/
         private static final String _CLASS_VERSION = "PARIAEmail - 1 - 24.06.2011";

         /** mailHost **/
         private static String mailHost = "mailhub.lss.emc.com";

         /** from **/
         private static String from =emailLink@xyz.com;

         /** fMailServerConfig **/
         private static Properties fMailServerConfig = new Properties();

         /** res **/
         private static ResourceBundle res = null;

         /** constructor **/
         public PARIAEmail() {
                    // log the class info
                    logger.info(_CLASS_VERSION);
         }

         /** static block **/
         static {
                    getConfig();
                    fetchConfig();
         }

        /** Open a specific text file containing mail server parameters, and populate
          * a corresponding Properties object.
          */
        private static void fetchConfig() {
                    fMailServerConfig.setProperty("mail.host", mailHost);
                    fMailServerConfig.setProperty("mail.from", from);
        }

        private static void getConfig() {
                    String _function = "getConfig()";
                    logger.info("Calling " + _function);

                    try {
                           res = ResourceBundle.getBundle("PTCApplicationResources");
                           Enumeration bundleKeys = res.getKeys();

                           while (bundleKeys.hasMoreElements()) {
                                     String key = bundleKeys.nextElement();
                                     if (key.equalsIgnoreCase("EMAIL.HOST"))
                                                mailHost = res.getString(key);

                                     if (key.equalsIgnoreCase("EMAIL.FROM"))
                                                from = res.getString(key);
                           }
                    } catch (Exception e) {
                                 logger.error("Error - Log.getConfig() " + e.toString());
                    }
        }

        /** Send a single email. */
        public void sendEmail(String aFromEmailAddr, String aToEmailAddr,
                   String aSubject, String aHTMLBody) throws PARIAException {
                   String _function = "sendEmail()";
                   Session session = Session.getDefaultInstance(fMailServerConfig, null);

                   MimeMessage message = new MimeMessage(session);

                   try {
                          message.setFrom(new InternetAddress(aFromEmailAddr));
                          message.addRecipient(Message.RecipientType.TO,

                                         new InternetAddress(aToEmailAddr));
                          message.setSubject(aSubject);

                          // add related mutip-part for root
                          MimeMultipart multipartRoot = new MimeMultipart("related");
                          MimeBodyPart contentRoot = new MimeBodyPart();
                          MimeMultipart multipartAlt = new MimeMultipart("alternative");

                          // alternative message
                          BodyPart messageBodyPart;
                          messageBodyPart = new MimeBodyPart();
                          String htmlText = aHTMLBody;
                          messageBodyPart.setContent(htmlText, "text/html");
                          multipartAlt.addBodyPart(messageBodyPart);

                          // Hierarchy
                          multipartRoot.addBodyPart(contentRoot);

                         // add multipart to the message
                         message.setContent(multipartRoot);
                         contentRoot.setContent(multipartAlt);

                         Transport.send(message);
                         logger.info(_CLASS_VERSION + " " + _function

                                   + " Email sent to: " + aToEmailAddr);
                 } catch (MessagingException ex) {
                         logger.error("Exception caught in " + this.getClass().getName()
                                   + ":" + ex.getStackTrace()[0].getMethodName() + "()" + ex);
                         throw new PARIAException("Exception caught in "
                                   + this.getClass().getName() + ":" + ex.getStackTrace()[0].getMethodName() + "()" + ex);
                 }
        }

        public void sendEmailKeys(String aFromEmailAddr, List aToEmailAddr,

                 String Subject, String aHTMLBody) throws PARIAException {

                 Session session = Session.getDefaultInstance(fMailServerConfig, null);
                 String _function = "sendEmailKeys()";
                 MimeMessage message = new MimeMessage(session);

                 try {
                        message.setFrom(new InternetAddress(aFromEmailAddr));
                        InternetAddress addressFrom = new InternetAddress(from);
                        message.setFrom(addressFrom);
                        int sizeTo = aToEmailAddr.size();
                        InternetAddress[] addressTo = new InternetAddress[sizeTo];
                        for (int i = 0; i < sizeTo; i++) {
                                  addressTo[i] = new InternetAddress(aToEmailAddr.get(i).toString());
                        }
                        message.setRecipients(Message.RecipientType.TO, addressTo);
                        message.setSubject(aSubject);

                        // add related mutip-part for root
                        MimeMultipart multipartRoot = new MimeMultipart("related");

                        // first part (the html)
                        BodyPart messageBodyPart = new MimeBodyPart();
                        String htmlText = aHTMLBody;
                        messageBodyPart.setContent(htmlText, "text/html");


                       /
/ add it
                       multipartRoot.addBodyPart(messageBodyPart);

                       // put everything together
                       message.setContent(multipartRoot);
                       Transport.send(message);
                       logger.info(_CLASS_VERSION + " " + _function

                                + " Email sent to: " + aToEmailAddr);
                } catch (MessagingException ex) {
                       logger.error("Exception caught in " + this.getClass().getName()
                                + ":" + ex.getStackTrace()[0].getMethodName() + "()" + ex);
                       throw new PARIAException("Exception caught in "
                                + this.getClass().getName() + ":" + ex.getStackTrace()[0].getMethodName() + "()" + ex);
                }
       }


       /**
         * This method send email if any error occures in LEAGUE to PTC response
         * @param responseStatus
         */

        public void sendResponseErrorEmail(ResponseStatus responseStatus) throws PARIAException {
                  String mailContent = null;
                  String subject = null;
                  String toEmailId = null;
                  String toEmailIds = null;
                  List ArrToEmailIds = null;
                  String fromAddress = null;
                  String fromEmailId = null;
                  String strResponse = null;


                  try {
                         if(responseStatus != null && responseStatus.getActivationId() != null               
                                 && responseStatus.getStatus().equals("ACTIV")){
                                 subject = "PTC Upstream " + responseStatus.getTrantsactionType()
                                                 + " Succeeded for Activation Id : " + responseStatus.getActivationId();

                                 mailContent = "Hi,";
                                 mailContent += "Activation succeeded for Entitlment Id "
                                                      + responseStatus.getEntitlementId()
                                                      + " , Activation Id : " + responseStatus.getActivationId()
                                                      + " Transaction Type : " + responseStatus.getTrantsactionType() + " ";

                                  strResponse = responseStatus.getStrResponseXml().replaceAll("<", "<");
                                  strResponse = strResponse.replaceAll(">", ">");
                                  mailContent += "PTC Upstream Response" + strResponse + " ";

                                  //toEmailId = res.getString("EMAIL.TOEMAIL");
                                  toEmailIds = res.getString("EMAIL.SUCCESSMULTITOEMAIL");
                                  fromAddress = res.getString("EMAIL.FROMADDRESS");
                                  fromEmailId = res.getString("EMAIL.FROMEMAIL");
                                  mailContent += "Thanks and Regards," + fromAddress;

                                  //sendEmail(fromEmailId, toEmailId, subject, mailContent);
                                  ArrToEmailIds = Arrays.asList(toEmailIds.split(";"));
                                  sendEmailKeys(fromEmailId, ArrToEmailIds, subject, mailContent);

                         } else if (responseStatus != null && responseStatus.getActivationId() != null
                                     && responseStatus.getStatus().equals("Error")) {
                                     subject = "PTC Upstream " + responseStatus.getTrantsactionType()
                                                    + " failed for Activation Id : " + responseStatus.getActivationId();

                                     mailContent = "Hi,";
                                     mailContent += "Error occured for Entitlment Id " + responseStatus.getEntitlementId()
                                                         + " , Activation Id : " + responseStatus.getActivationId()
                                                         + " Transaction Type : " + responseStatus.getTrantsactionType() + " ";
                                     if (responseStatus.getErrorId() != null) {
                                              mailContent += "Error Id : " + responseStatus.getErrorId() + " ";
                                     }
                                     if (responseStatus.getErrorDesc() != null) {
                                              mailContent += "Error Description : " + responseStatus.getErrorDesc() + " ";
                                     }
                                     if (responseStatus.getErrorId() == null && responseStatus.getErrorDesc() == null) {
                                              mailContent += "Undefined Error : Error id and Description not found.";
                                     }
                                     strResponse = responseStatus.getStrResponseXml().replaceAll("<", "<");
                                     strResponse = strResponse.replaceAll(">", ">");
                                     mailContent += "PTC Upstream Response" + strResponse + " ";

                                     //toEmailId = res.getString("EMAIL.TOEMAIL");
                                     toEmailIds = res.getString("EMAIL.FAILMULTITOEMAIL");
                                     fromAddress = res.getString("EMAIL.FROMADDRESS");
                                     fromEmailId = res.getString("EMAIL.FROMEMAIL");
                                     mailContent += "Thanks and Regards," + fromAddress;

                                     //sendEmail(fromEmailId, toEmailId, subject, mailContent);
                                     ArrToEmailIds = Arrays.asList(toEmailIds.split(";"));
                                     sendEmailKeys(fromEmailId, ArrToEmailIds, subject, mailContent);
                          }

                  } catch (Exception e) {
                          logger.error("Exception caught in " + this.getClass().getName()
                                    + ":" + e.getStackTrace()[0].getMethodName() + "()" + e);
                          throw new PARIAException("Exception caught in " + this.getClass().getName() + ":"
                                    + e.getStackTrace()[0].getMethodName() + "()" + e);
                  }

        }
}


Properties file
#EMAIL Properites
EMAIL.HOST = mailhub.lss.XXX.com
EMAIL.ENVIRONMENT = DEV
#EMAIL.FROM = royelti@XXX.com
EMAIL.FROM = royelti@XXX.com
EMAIL.FROMEMAIL = from.admin@XXX.com
EMAIL.SUCCESSTOEMAIL = arun.paria@XXX.com
EMAIL.SUCCESSMULTITOEMAIL = arun.paria@XXX.com;arun.paria@XXX.com
EMAIL.FAILTOEMAIL = arun.paria@XXX.com
EMAIL.FAILMULTITOEMAIL = arun.paria@XXX.com;arun.paria@XXX.com
EMAIL.DEFUALT = elm_testers@XXX.com;beejer13@gmail.com
EMAIL.FROMADDRESS = Upstream
PARIA Team


 

No comments:

Post a Comment