package ibase.utility;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
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 javax.mail.search.FlagTerm;
import javax.mail.util.ByteArrayDataSource;
import javax.naming.InitialContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.InputSource;
import java.io.StringReader;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ibase.communication.WhatsAppComm;
import ibase.ejb.E12SMSComp;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.notification.ejb.PublishPushNotificationEJB;
import ibase.webitm.notification.ejb.PublishPushNotificationLocal;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.ITMMailInfo;
import ibase.wrkflw.WorkflowProcessInstanceMonitorEJB;

public class EMail
{
	String emailType = null;
	String xmlDataFilePath = null;
	//vikrant-start 27/03/2006 intialise null
	String toAddr = null;
	String ccAddr = null;
	String bccAddr = null;
	String subject = null;
	String message = null;
	//Added by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail
	String messageType = null;
	//Added by Samadhan[S16FKAT002] on 17/03/2017 for send inlineImages body mail
	HashMap<String, String> inlineImages = null;
	//Danish Tuesday, June 13, 2006 Start
	//String objName = null;
	//String refSer = null;
	//String refID = null;
	//String lineNo = null;
	//Danish Tuesday, June 13, 2006 End
	//vikrant-end 27/03/2006

	// Added by Abhishek T on 20-June-18 [For sending notification] START
	private String entityCodes;
	private DBAccessEJB dbAccess = null; //added  by amol s

	// Added by Abhishek T on 20-June-18 [For sending notification] END

	//Added by Gulzar/Gaurav Singh on 29-05-14 [ Start ]
	//To set the sender id dynamically. If found will set otherwise will set from CommonConstant.MAILFROM
	String mailFrom = null;
	public String getMailFrom()
	{
		return mailFrom;
	}

	public void setMailFrom(String mailFrom)
	{
		this.mailFrom = mailFrom;
	}
	//Added by Gaurav Singh on 29-05-14 [ End ]

	public void setEmailType(String emailType)
	{
		this.emailType = emailType;
	}

	public void setXMLDataFilePath(String xmlDataFilePath)
	{
		this.xmlDataFilePath = xmlDataFilePath;
	}
	
	//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
	private static String username = "";
	private static String password = "";
	//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END

	//public String sendMail(String mailXMLStr)throws Exception //Danish 27-03-2006
	//To be called from wrkflow only
	//Changed by Gulzar to pass the connection param on 28/05/15 : START
	public String sendMail(String mailXMLStr, String infoType, String processInstanceId)throws Exception
	{
		String returnVal = "";
		Connection conn = null;//Gulzar on 28/05/15
		try
		{
			sendMail( mailXMLStr, infoType, processInstanceId, conn);
		}
		catch (Exception e)
		{
			throw e;
		}
		return returnVal;
	}

	// Added by Abhishek T on 15-May-18 [For Lloyd changes] START
	public String sendMail(String mailXMLStr, String infoType, String processInstanceId, Connection conn)
			throws Exception {
		return sendMail(mailXMLStr, infoType, processInstanceId, "false", null, conn);
	}
	// Added by Abhishek T on 15-May-18 [For Lloyd changes] END

	// Changed by Abhishek T on 15-May-18 [For sending notification with mail] START
	public String sendMail(String mailXMLStr, String infoType, String processInstanceId, String sendNotification, String userInfo, Connection conn) throws Exception
	{
		String returnVal = "";
		try
		{
			//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
			//Changed By Pankaj T on 04-05-2020 Comment changes temporary for workflow issue. After done workflow changes need to uncomment. 
			returnVal = sendMail(mailXMLStr, infoType, conn);
			//UserInfoBean userInfoBean = new UserInfoBean(userInfo);
			//returnVal = sendMail(mailXMLStr, infoType, userInfoBean);
			//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end
			
			BaseLogger.log("3",null,null,"returnVal [sendMail] =["+returnVal+"]");
			if("S".equals(returnVal) && processInstanceId != null )
			{
				// Added by Abhishek T on 20-June-18 [For sending notification] START
				BaseLogger.log("3",null,null,"EMail :: sendMail() : Sending Notification : Send Notification [" + sendNotification + "]");
				if ("true".equalsIgnoreCase(sendNotification)) {
					if (entityCodes != null && !"".equals(entityCodes.trim())) {
						BaseLogger.log("3",null,null,"EMail :: sendMail() : Sending Notification : Entity Codes [" + entityCodes + "]");

						try {
							UserInfoBean userInfoBean = new UserInfoBean(userInfo);

							String[] entityCodeArray = entityCodes.split(",");
							List<String> list = Arrays.asList(entityCodeArray);
							ArrayList<String> entityCodesList = new ArrayList<String>(list);

							sendNotification(mailXMLStr, entityCodesList, userInfoBean);
						} catch (Exception ex) {
							BaseLogger.log("0",null,null,"Exception in EMail :: sendMail() : Sending Notification " + ex);
						}
					}
				}
				// Added by Abhishek T on 20-June-18 [For sending notification] END

				BaseLogger.log("3",null,null,"Marking Activity Done.");
				AppConnectParm appConnect = new AppConnectParm();
				java.util.Properties p = appConnect.getProperty();
				InitialContext ctx = new InitialContext(p);
				/*WorkflowProcessInstanceMonitorHome instanceMonitorHome = (WorkflowProcessInstanceMonitorHome)ctx.lookup("WorkflowProcessInstanceMonitor");
				WorkflowProcessInstanceMonitor workflowProcessInstanceMonitor = instanceMonitorHome.create();*/

				//Changes made by Gulzar on 29/05/15 : START
				//Changed from remote look up to local look up to avoid UndeclaredThrowableException as connection is passed.
				//same connection is used to update the status instead of separate one.
				//WorkflowProcessInstanceMonitorRemote workflowProcessInstanceMonitor = (WorkflowProcessInstanceMonitorRemote)ctx.lookup("ibase/WorkflowProcessInstanceMonitorEJB/remote");
				// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
				//WorkflowProcessInstanceMonitorLocal workflowProcessInstanceMonitor = (WorkflowProcessInstanceMonitorLocal)ctx.lookup("ibase/WorkflowProcessInstanceMonitorEJB/local");
				WorkflowProcessInstanceMonitorEJB workflowProcessInstanceMonitor = new WorkflowProcessInstanceMonitorEJB();
				// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]

				//Changed By Danish on 24/07/2006 reason [encoporating common method for updating status of wrkflw].
				BaseLogger.log("3",null,null,"Calling workflowProcessInstanceMonitor.updateActivityStatus with '2' from sendMail");
				String resultXmlStr = "<ROOT><STATUS><![CDATA[1]]></STATUS><RESULT><![CDATA[S]]></RESULT></ROOT>";
				if(conn != null)
				{
					workflowProcessInstanceMonitor.updateActivityStatus( processInstanceId, "2", "", "", "", "", "", resultXmlStr, conn);
				}
				else
				{
					workflowProcessInstanceMonitor.updateActivityStatus( processInstanceId, "2", "", "", "", "", "", resultXmlStr);
				}
				workflowProcessInstanceMonitor = null;
				//Changes made by Gulzar on 29/05/15 : END
				//workflowProcessInstanceMonitor.markActivityDone(processInstanceId, null, null, null); commented by Danish on 24/07/2006
			}
		}
		catch (Exception e)
		{
			throw e;
		}
		return returnVal;
	}
	//Changed by Gulzar to pass the connection param on 28/05/15 : END
	// Changed by Abhishek T on 15-May-18 [For sending notification with mail] END

	/**
	 * Sends device notification to given users.
	 *
	 * @param mailXMLString The xml string, provides necessary information
	 * 						for sending notification
	 * @param userIdList The user id list
	 * @param userInfoBean Contains user information
	 */
	private void sendNotification(String mailXMLString, ArrayList<String> userIdList, UserInfoBean userInfoBean) {
		try {
			E12GenericUtility e12GenericUtility = new E12GenericUtility();
			Document mailXMLDocument = e12GenericUtility.parseString(mailXMLString);
			Map<String, String> infoMap = createMap(mailXMLDocument);

			String notificationLabel = "Notification";

			// Added by Abhishek T on 16-July-18 [For getting notification message label from xml string] START
			Node notificationLabelNode = mailXMLDocument.getElementsByTagName("NOTIFICATION_LABEL").item(0);
			if (notificationLabelNode != null) {
				notificationLabel = notificationLabelNode.getTextContent();

				if (notificationLabel != null) {
					notificationLabel = notificationLabel.trim();
				}
			}
			// Added by Abhishek T on 16-July-18 [For getting notification message label from xml string] END

			String objName = infoMap.get("OBJ_NAME");
			String refSer = infoMap.get("REF_SER");
			String refId = infoMap.get("REF_ID");
			String lineNo = infoMap.get("LINE_NO");
			String userCode = userInfoBean.getLoginCode();

			StringBuilder xmlDataBuilder = new StringBuilder("<ROOT>");
	        xmlDataBuilder.append(createXMLTag("OBJ_NAME", objName))
		      			  .append(createXMLTag("REF_SER", refSer))
		      			  .append(createXMLTag("REF_ID", refId))
		      			  .append(createXMLTag("LINE_NO", lineNo))
		      			  .append(createXMLTag("USER_ID", userCode))
		      			  .append(createXMLTag("SERVER_URL",CommonConstants.TOMCAT_HOME))
		      			  .append(createXMLTag("SITE_CODE", userInfoBean.getSiteCode()))
		      			  .append("</ROOT>");

	        int lineNumber = 0;
	        try {
	        	lineNumber = Integer.parseInt(lineNo);
	        } catch (Exception ex) {
	        	lineNumber = 1;
	        }

			publishPushNotificationEJB().invockPushNotification (
				notificationLabel, userCode, PublishPushNotificationLocal.OPEN_TARGET_SOCIAL,
	    		refId, userIdList, xmlDataBuilder.toString(), refId, refSer, userCode,
	    		lineNumber, "S", userInfoBean
	        );
		} catch (Exception ex) {
			BaseLogger.log("0",null,null,"Exception in EMail :: sendNotification() : " + ex);
		}
	}

	private Map<String, String> createMap(Document mailXMLDocument)
			throws ITMException {

		Map<String, String> resultMap = new HashMap<String, String>();

		E12GenericUtility genericUtility = new E12GenericUtility();

		if (mailXMLDocument != null) {
			NodeList detail1List = mailXMLDocument.getElementsByTagName("Root");

			if (detail1List != null && detail1List.getLength() > 0) {
				Node detail1Node = detail1List.item(0);

				String objName = genericUtility.getColumnValueFromNode("OBJ_NAME", detail1Node);
				String refSer = genericUtility.getColumnValueFromNode("REF_SER", detail1Node);
				String refId = genericUtility.getColumnValueFromNode("REF_ID", detail1Node);
				String lineNo = genericUtility.getColumnValueFromNode("LINE_NO", detail1Node);

				resultMap.put("OBJ_NAME", objName);
				resultMap.put("REF_SER", refSer);
				resultMap.put("REF_ID", refId);
				resultMap.put("LINE_NO", lineNo);
			}

		}

		return resultMap;
	}

	String createXMLTag (String tagName, String value) {
		return ("<" + tagName + "><![CDATA[" + value + "]]></" + tagName + ">");
	}

	private PublishPushNotificationEJB publishPushNotificationEJB() throws BaseException
	{
		//PublishPushNotificationLocal pushNotificationObj = null;
		PublishPushNotificationEJB publishPushNotificationEJB = null;

		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			//pushNotificationObj = (PublishPushNotificationLocal)ctx.lookup("ibase/PublishPushNotificationEJB/local");
			publishPushNotificationEJB = new PublishPushNotificationEJB();
		}
		catch (BaseException be)
		{
			BaseLogger.log("0",null,null,"Exception: publishPushNotificationEJB:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception: publishPushNotificationEJB:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}

		return publishPushNotificationEJB;
	}

	public String sendMail(String mailXMLStr, String infoType)throws Exception
	{
		boolean debug = false;
		boolean success = false;

		File createdFileObj = null;
		//Added By Prasahnt Chavan 03-Sep-15 [Request ID B15ESUN001]
		ArrayList<File> attachmentList = new ArrayList<File>();
		BaseLogger.log( "3", null, null, "mailXMLStr : ["+ mailXMLStr +"]" );

		try
		{
			ibase.utility.MailInfo mailInfo = null;
			//vikrant 27/03/2006
			if ("ITM".equalsIgnoreCase(infoType))
			{
				Class mailInfoClass = Class.forName( "ibase.webitm.utility.ITMMailInfo" );
				mailInfo = ( ibase.utility.MailInfo ) mailInfoClass.newInstance();
			}
			else
			{
				mailInfo = new ibase.utility.MailInfo();
			}
			mailInfo.setMailProp(mailXMLStr);

			StringTokenizer st_to = null;
			StringTokenizer st_cc = null;
			StringTokenizer st_bcc = null;

			//getThe to, cc and bcc addresses and pass it to st of corresponding
			this.toAddr = mailInfo.getToAddr();
			this.ccAddr = mailInfo.getCcAddr();
			this.bccAddr = mailInfo.getBccAddr();
			this.subject = mailInfo.getSubject();
			this.message =  mailInfo.getMessage();
			this.emailType =  mailInfo.getEmailType();
			//Added by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail
			this.messageType = mailInfo.getMessageType();
			//Added by Samadhan[S16FKAT002] on 23/03/2017 for send inline images in body mail
			this.inlineImages = mailInfo.getInlineImages();

			//Added by Gulzar/Gaurav Singh on 29-05-14 to set the mail_from received from mailInfoStr
			this.mailFrom = mailInfo.getMailFrom();

			/* //Danish Tuesday, June 13, 2006
			this.objName = mailInfo.getObjName();
			this.refSer = mailInfo.getRefSer();
			//this.refID = mailInfo.getRefID();
			//this.lineNo = mailInfo.getLineNo(); //Danish Tuesday, June 13, 2006*/
			this.xmlDataFilePath = mailInfo.getXmlDataFilePath();
			InternetAddress[] toaddress = null;
			InternetAddress[] ccaddress = null;
			InternetAddress[] bccaddress = null;
			//Added by Gaurav Singh on 29-05-14
			InternetAddress from = null;

			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | Start ]
			//CommonConstants.setIBASEHOME();
			if(CommonConstants.TOMCAT_HOME == null || CommonConstants.TOMCAT_HOME.trim().length() == 0)
			{
				CommonConstants.setIBASEHOME();
			}
			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | End ]

			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
			/*Properties props= new Properties();
			props.put("mail.smtp.host", CommonConstants.SMTPHOST);

			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :START
			if(CommonConstants.SMTPPORT != null && CommonConstants.SMTPPORT.trim().length() > 0)
			{
				props.put("mail.smtp.port", CommonConstants.SMTPPORT);
			}
			if(CommonConstants.PROTOCOL_TYPE != null && "SSL".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			}
			else if(CommonConstants.PROTOCOL_TYPE != null && "TLS".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.starttls.enable", "true");
			}*/
			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :END

			Session session = null;
			if ( CommonConstants.smtpSessions != null && CommonConstants.smtpSessions.get( CommonConstants.USERNAME ) != null )
			{
				//Changed by Prasad R on 16/12/2020 [set global credentials value while set session from smtpSessions]
				BaseLogger.log( "3", null, null, "set session from existing smtpSessions" );
				username = CommonConstants.USERNAME;
				password = CommonConstants.PASSWORD;
				session = CommonConstants.smtpSessions.get( CommonConstants.USERNAME );
				BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
			}
			else
			{
				Properties props = createIbaseMailServerProperties();
				Authenticator auth = null;
				if( CommonConstants.USERNAME != null && CommonConstants.PASSWORD != null )
				{
					props.put("mail.smtp.auth","true");
					//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
					//auth = new SMTPAuthenticator(null, false);
					auth = new SMTPAuthenticator();
					username = CommonConstants.USERNAME;
					password = CommonConstants.PASSWORD;
					BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
				}
				BaseLogger.log( "3", null, null, "props : ["+ props +"]" );
				session = Session.getInstance(props,auth);
				if ( CommonConstants.smtpSessions == null )
				{
					CommonConstants.smtpSessions = new HashMap<String, Session>();
				}
				CommonConstants.smtpSessions.put( CommonConstants.USERNAME, session );
			}
			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END
			session.setDebug(debug);
			//create message
			MimeMessage msg = new MimeMessage(session);

			//Commented and changes made by Gaurav Singh on 29-05-14 [ Start ]
			//To set the sender id dynamically. If found will set otherwise will set from CommonConstant.MAILFROM
			//InternetAddress from = new InternetAddress(CommonConstants.MAILFROM);
			if(this.mailFrom != null && this.mailFrom.trim().length() > 0)
		    {
		       from = new InternetAddress(this.mailFrom);
		    }
		    else
		    {
		       from = new InternetAddress(CommonConstants.MAILFROM);
		    }
			//Commented and changes made by Gaurav Singh on 29-05-14 [ End ]

			msg.setFrom(from);

			if(this.toAddr != null && ! this.toAddr.trim().equals("") && ! this.toAddr.equalsIgnoreCase("null"))
			{
				st_to = new StringTokenizer(this.toAddr,",");
				toaddress = new InternetAddress[st_to.countTokens()];
				int ctr = 0;
				while(st_to.hasMoreTokens())
				{
					InternetAddress address=new InternetAddress(st_to.nextToken());
					toaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("0",null,null,"[EMail]Setting to Recipients .........");
				msg.setRecipients(Message.RecipientType.TO,toaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: To Address :"+this.toAddr);
			}

			int ctr = 0;
			if (this.ccAddr != null && !this.ccAddr.trim().equals("") && !this.ccAddr.equalsIgnoreCase("null") )
			{
				st_cc = new StringTokenizer(this.ccAddr,",");
				ctr = 0;
				ccaddress = new InternetAddress[st_cc.countTokens()];
				while(st_cc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_cc.nextToken());
					ccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting cc Recipients .........");
				msg.setRecipients(Message.RecipientType.CC,ccaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: ccAddress :"+this.ccAddr);
			}

			if (this.bccAddr != null && !this.bccAddr.trim().equals("") && !this.bccAddr.equalsIgnoreCase("null") )
			{
				st_bcc = new StringTokenizer(this.bccAddr,",");
				ctr = 0;
				bccaddress=new InternetAddress[st_bcc.countTokens()];
				while(st_bcc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_bcc.nextToken());
					bccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting bcc Recipients .........");
				msg.setRecipients(Message.RecipientType.BCC,bccaddress);
			}
			else //vikrant 27/03/2006
			{
				BaseLogger.log("3",null,null,"Warning: bccAddress :"+this.bccAddr);
			}

			//Message Properties Setting
			//vikrant 27/03/2006
			if(this.subject!=null && !this.subject.trim().equalsIgnoreCase("null"))
			{
				msg.setSubject(subject);
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: Subject Not Defined !!!");
			}
			msg.setSentDate(new Date());

			//Message Body Creation
			BodyPart messageBody = new MimeBodyPart();
			BodyPart msgBodyForPage = null;
			BodyPart msgBodyForLink = null;
			Multipart multipart = new MimeMultipart();

			//part one: text message
			//vikrant 27/03/2006
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]Start
			/*if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
			{
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail start.
				//messageBody.setText(this.message);
				BaseLogger.log("9",null,null,"this.messageType:"+this.messageType);
				if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
				{
					messageBody.setContent(this.message, this.messageType);
				}else
				{
					messageBody.setText(this.message);
				}
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail end.
			}
			else
			{
				BaseLogger.log("9",null,null,"Warning: Message Not Defined !!!");
				messageBody.setText("");
			}
			multipart.addBodyPart(messageBody);*/
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]End
			//Samadhan
			if(inlineImages != null)
			{
				for (String key : inlineImages.keySet())
				{
					MimeBodyPart messageBodyPart1 = new MimeBodyPart();
					DataSource fds = new FileDataSource(inlineImages.get(key));
					messageBodyPart1.setDataHandler(new DataHandler(fds));
					messageBodyPart1.setHeader("Content-ID", "<"+key+">");
					multipart.addBodyPart(messageBodyPart1);
					BaseLogger.log("3",null,null,"inline path:"+inlineImages.get(key));
				}
			}
			//part two: attachment
			//vikrant 27/03/2006
			if (this.emailType != null && this.emailType.trim().length() > 0 && !this.emailType.trim().equalsIgnoreCase("null"))
			{
				if(this.emailType.equals("page"))
				{
					//vikrant 27/03/2006
					if (this.xmlDataFilePath != null)
					{
						//Changed By Prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] Start
						/*createdFileObj = new File(this.xmlDataFilePath);
						msgBodyForPage = new MimeBodyPart();
						DataSource source = new FileDataSource(createdFileObj);
						msgBodyForPage.setDataHandler(new DataHandler(source));
						BaseLogger.log("9",null,null,createdFileObj);

						//Changed by Gulzar on 07/11/14 - START
						//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
						}
						else
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						}
						//Changed by Gulzar on 07/11/14 - END
						BaseLogger.log("9",null,null,"File name :"+msgBodyForPage.getFileName()+":");
						multipart.addBodyPart(msgBodyForPage);*/
						if(this.xmlDataFilePath.indexOf(";") != -1)
						{
							BaseLogger.log("3",null,null,"xmlDataFilePath"+this.xmlDataFilePath);
							String[] dataFilePathArry = this.xmlDataFilePath.split(";");
							BaseLogger.log("3",null,null,"dataFilePathArry length [ "+dataFilePathArry.length+" ]");
							for(int i = 0; i < dataFilePathArry.length; i++)
							{
								createdFileObj = new File(dataFilePathArry[i]);
								msgBodyForPage = new MimeBodyPart();
								DataSource source = new FileDataSource(createdFileObj);
								msgBodyForPage.setDataHandler(new DataHandler(source));
								BaseLogger.log("3",null,null,createdFileObj);

								//Changed by Gulzar on 07/11/14 - START
								//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
								}
								else
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								}
								//Changed by Gulzar on 07/11/14 - END
								BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
								multipart.addBodyPart(msgBodyForPage);
								//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
								attachmentList.add(createdFileObj);
							}
						}
						else
						{
							createdFileObj = new File(this.xmlDataFilePath);
							msgBodyForPage = new MimeBodyPart();
							DataSource source = new FileDataSource(createdFileObj);
							msgBodyForPage.setDataHandler(new DataHandler(source));
							BaseLogger.log("3",null,null,createdFileObj);

							//Changed by Gulzar on 07/11/14 - START
							//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
							}
							else
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							}
							//Changed by Gulzar on 07/11/14 - END
							BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
							multipart.addBodyPart(msgBodyForPage);
							//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
							attachmentList.add(createdFileObj);
						}
						//Added By prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] End
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: xmlDataFilePath :"+xmlDataFilePath);
					}
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][Start]
					if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
					{
						BaseLogger.log("3",null,null,"line no:441...this.messageType:"+this.messageType);
						if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
						{
							messageBody.setContent(this.message, this.messageType);
						}else
						{
							messageBody.setText(this.message);
						}
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
						messageBody.setText("");
					}
					multipart.addBodyPart(messageBody);
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][End]
				}
				if(this.emailType.equals("link"))
				{
					//createdFileObj = mailInfo.getLinkFileObj(this.objName, this.refSer,  this.refID, this.lineNo); //builds the link to be send  //Danish Tuesday, June 13, 2006
					//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]
					createdFileObj = mailInfo.getLinkFileObj( this.message ); //builds the link to be send
					msgBodyForLink = new MimeBodyPart();
					DataSource source = new FileDataSource(createdFileObj);
					msgBodyForLink.setDataHandler(new DataHandler(source));
					BaseLogger.log("3",null,null,"FileObjCreated ..."+ createdFileObj);
					multipart.addBodyPart(msgBodyForLink);
					//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
					attachmentList.add(createdFileObj);
				}
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: emailType not found !!!");
				//Changed by Anjali R.[10/09/2017][Start][For bug fixing in system generated emails]
				if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
				{
					BaseLogger.log("3",null,null,"this.messageType:"+this.messageType);
					if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
					{
						messageBody.setContent(this.message, this.messageType);
					}
					else
					{
						if(this.message.toLowerCase().indexOf("<html>") != -1)
						{
							messageBody.setContent(this.message, "text/html; charset=utf-8");
						}
						else
						{
							messageBody.setText(this.message);
						}
					}
				}
				else
				{
					BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
					messageBody.setText("");
				}
				multipart.addBodyPart(messageBody);
				//Changed by Anjali R.[10/09/2017][End][For bug fixing in system generated emails]
			}
			msg.setContent(multipart);// Put parts in message
			BaseLogger.log("3",null,null,"[EMail]Sending Mail..............................");
			if(msg.getRecipients(Message.RecipientType.TO) != null || msg.getRecipients(Message.RecipientType.CC) != null || msg.getRecipients(Message.RecipientType.BCC) != null)
			{
				Transport.send(msg);
			}

			BaseLogger.log("3",null,null,"[EMail]Message Sent ...");
			//Changed by Prashant Chavan on 04-Sep-15 for deleting the Multiple Attachments Start
			/*if(createdFileObj!= null)
			{
				createdFileObj.delete(); //deleting the temp file
			}*/
			if( attachmentList.size() > 0)
			{
				for(int i = 0;i < attachmentList.size(); i++)
				{
					File attachmentFileObj = attachmentList.get(i);
					attachmentFileObj.delete();
				}
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception :EMail :sendMail :==>\n"+e.getMessage());
			e.printStackTrace();
			throw e;
		}
		return "S";
	}

	private class SMTPAuthenticator extends javax.mail.Authenticator
	{
		//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
		//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
		/*public UserInfoBean userInfo = null;
		boolean SMTPConn;
		SMTPAuthenticator( UserInfoBean userInfo, boolean SMTPConn )
		{
			this.userInfo = userInfo;
			this.SMTPConn = SMTPConn;
		}
		//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end
		*/
		//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END
	    public PasswordAuthentication getPasswordAuthentication()
		{
			try
			{
				//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
				/*BaseLogger.log("2", null, null, "In SMTPAuthenticator getPasswordAuthentication is SMTP conn :["+this.SMTPConn+"]");
				String username = CommonConstants.USERNAME;
				String password = CommonConstants.PASSWORD;
				//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
				if( this.userInfo != null && E12GenericUtility.checkNull(this.userInfo.getSmtpHost()).length() > 0 && this.SMTPConn )
				{
					username = this.userInfo.getSmtpUser();
					password = this.userInfo.getSmtpPassWD();
				}
				//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end
				*/
				BaseLogger.log("2", null, null, "In SMTPAuthenticator getPasswordAuthentication :: username : ["+ username +"], password : ["+ password +"]");
				return new PasswordAuthentication(username, password);
				//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END
			}
			catch(Exception e)
			{
				BaseLogger.log("0",null,null,"Exception :EMail :SMTPAuthenticator :==>\n"+e.getMessage());
				return null;
			}
		}
	}
	//Added by Pankaj T on 12-01-18 [changes for multitenancy add overloaded method] - Start
	public String sendMail(String mailXMLStr, String infoType, UserInfoBean userInfo)throws Exception
	{
		BaseLogger.log("3", userInfo, null, "Method  Called sendMail mailXMLStr[" + mailXMLStr +"]");

		E12GenericUtility e12GenericUtility = new E12GenericUtility(); // Added by Gagan B. for inserting error message in comm_log on 28-JUL-2022.

		//Added by Amol S  on 15-may-25 to parse the DOM and extract the value-start
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder builder = factory.newDocumentBuilder();
	    Document doc = builder.parse(new InputSource(new StringReader(mailXMLStr)));

	    // Step 2: Extract the TEMPLATE_CODE from the Document
	    String templateCode = null;
	    NodeList templateNodes = doc.getElementsByTagName("TEMPLATE_CODE");
	    if (templateNodes != null && templateNodes.getLength() > 0) {
	        templateCode = templateNodes.item(0).getTextContent().trim();
	    }
		BaseLogger.log("3", userInfo, null, " TEMPLATE_CODE: ===>" + templateCode);
		
		String toAddress = null;
		NodeList toNodes = doc.getElementsByTagName("TO_ADD");
		if (toNodes != null && toNodes.getLength() > 0) {
			toAddress = toNodes.item(0).getTextContent().trim();
		}
		BaseLogger.log("3", userInfo, null, " toAddress : ===>" + toAddress);

		//String actionInfo="";
		String msgType = getDBAccess().getDBColumnValue("MAIL_FORMAT", "MSG_TYPE",
				(" FORMAT_CODE = '" + templateCode + "' "), userInfo.getTransDB());
		BaseLogger.log("3", null, null, "MsgType::: [" + msgType + "]");
		
		//Added by Amol S  on 15-may-25 to parse the DOMand extract the value-End
		//Amol -strt
	    if("B".equalsIgnoreCase(msgType))
		{
			BaseLogger.log("3", null, null, "Inside the B block ");
			
			sendEmailAndSms(templateCode,mailXMLStr, userInfo);
		    return "S";
		}
		
		//Added by Amol S on 13-Jun-25 to send email,sms,whstaappMsg simeltenously
		// Added by Amol S on 13-Jun-25 to send Email, SMS, WhatsApp Msg simultaneously -Start
		else if ("A".equalsIgnoreCase(msgType)) {
		    BaseLogger.log("3", null, null, "Inside the A block - sending Email, SMS, and WhatsApp");

		    sendEmailAndSmsNdWhtsApp(templateCode, mailXMLStr, userInfo);
		    BaseLogger.log("3", null, null, "Method called============>>");
 
		    return "S";
		    
		}
		// Added by Amol S on 13-Jun-25 to send Email, SMS, WhatsApp Msg simultaneously -End
		else {
			//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start

			try
			{
				String smtpServerStatus = "";
				String smtpFallback = ""; // Added by Gagan B.
				if( userInfo != null )
				{
					DBAccessEJB dbAccessEJB = new DBAccessEJB();
					smtpServerStatus = dbAccessEJB.getDBColumnValue("ENTERPRISE", " SMTP_SERVER_STATUS", "ENTERPRISE  = '"+userInfo.getEnterprise()+"'", userInfo.getTransDB());
					// Added by Gagan B for getting SMTP_FALLBACK value from ENTERPRISE table. [START]
					smtpFallback = dbAccessEJB.getDBColumnValue("ENTERPRISE", " SMTP_FALLBACK", "ENTERPRISE  = '"+userInfo.getEnterprise()+"'", userInfo.getTransDB());
					// Added by Gagan B for getting SMTP_FALLBACK value from ENTERPRISE table. [END]
				}
				BaseLogger.log("3", userInfo, null, "EMail.sendMail() smtpServerStatus:["+smtpServerStatus+"]");
				if( userInfo != null && E12GenericUtility.checkNull(userInfo.getSmtpHost()).length() > 0 && !("INVALID_STATE".equalsIgnoreCase(E12GenericUtility.checkNull(smtpServerStatus))) )
				{
					return sendMailUsingSMTP(mailXMLStr, infoType, userInfo);
				}
				else
				{
					// Added by Gagan B. to add SMTP_FALLBACK configuration on 28-JUL-22. -- START
					if(!smtpFallback.equalsIgnoreCase("Y"))
					{
						e12GenericUtility.writeCommunicationLog(userInfo, false, "E", "F", "Your SMTP configuration seems to be in invalid state and you have not configured SMTP Fallback with us!", this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, 0, null);
						return "Value of SMTP_FALLBACK is not Y.";
					}
					// Added by Gagan B. to add SMTP_FALLBACK configuration on 28-JUL-22. -- END
					return sendMailUsingIBASE(mailXMLStr, infoType, userInfo);
				}
			}
			catch (Exception e)
			{
				throw e;
			}
		}

		
		
	}
	//Added by Pankaj T on 12-01-18 [changes for multitenancy add overloaded method] - Start
	
	
	//Added overriden methon by Ajit on 12-JAN-26 [START]
	public String sendMail(String mailXMLStr, String infoType, UserInfoBean userInfo, String tranXmlString)throws Exception
	{
		BaseLogger.log("3", userInfo, null, "Method  Called sendMail mailXMLStr[" + mailXMLStr +"]");
		BaseLogger.log("3", userInfo, null, "Method  Called sendMail tranXmlString[" + tranXmlString +"]");

		E12GenericUtility e12GenericUtility = new E12GenericUtility(); // Added by Gagan B. for inserting error message in comm_log on 28-JUL-2022.

		//Added by Amol S  on 15-may-25 to parse the DOM and extract the value-start
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder builder = factory.newDocumentBuilder();
	    Document doc = builder.parse(new InputSource(new StringReader(mailXMLStr)));

	    // Step 2: Extract the TEMPLATE_CODE from the Document
	    String templateCode = null;
	    NodeList templateNodes = doc.getElementsByTagName("TEMPLATE_CODE");
	    if (templateNodes != null && templateNodes.getLength() > 0) {
	        templateCode = templateNodes.item(0).getTextContent().trim();
	    }
		BaseLogger.log("3", userInfo, null, " TEMPLATE_CODE: ===>" + templateCode);
		
		String toAddress = null;
		NodeList toNodes = doc.getElementsByTagName("TO_ADD");
		if (toNodes != null && toNodes.getLength() > 0) {
			toAddress = toNodes.item(0).getTextContent().trim();
		}
		BaseLogger.log("3", userInfo, null, " toAddress : ===>" + toAddress);

		//String actionInfo="";
		String msgType = getDBAccess().getDBColumnValue("MAIL_FORMAT", "MSG_TYPE",
				(" FORMAT_CODE = '" + templateCode + "' "), userInfo.getTransDB());
		BaseLogger.log("3", null, null, "MsgType::: [" + msgType + "]");
		
		if("W".equalsIgnoreCase(msgType))
		{
			// Fetch BODY node from mail XML
			Node bodyNode = doc.getElementsByTagName("MESSAGE").item(0);
			String bodyValue = bodyNode.getTextContent();
			BaseLogger.log("3", null, null, "WhatsApp bodyValue ::: [" + bodyValue + "]");

			// Fetch WhatsApp config JSON from DB
			String whatsappConfig = getDBAccess().getDBColumnValue("ENTERPRISE", "WHATSAPP_SETTING",
					"ENTERPRISE = '" + userInfo.getEnterprise() + "'", userInfo.getTransDB());

			BaseLogger.log("3", null, null, "WhatsApp Config (Before) ::: [" + whatsappConfig + "]");

			try {
				if (bodyNode != null && whatsappConfig != null && whatsappConfig.trim().length() > 0) {

					if (bodyValue != null && bodyValue.trim().length() > 0) {

						// Parse WhatsApp config JSON
						JSONObject configObj = new JSONObject(whatsappConfig);

						// Get parameters array (create if missing)
						JSONArray paramsArray;
						if (configObj.has("parameters")) {
							paramsArray = configObj.getJSONArray("parameters");
						} else {
							paramsArray = new JSONArray();
							configObj.put("parameters", paramsArray);
						}

						// BODY contains JSON → add to parameters
						bodyValue = bodyValue.trim();

						if (bodyValue.startsWith("[")) {
							// Multiple parameters
							JSONArray bodyArray = new JSONArray(bodyValue);
							for (int i = 0; i < bodyArray.length(); i++) {
								paramsArray.put(bodyArray.getJSONObject(i));
							}
						} else {
							// Single parameter
							paramsArray.put(new JSONObject(bodyValue));
						}

						// Update config string
						whatsappConfig = configObj.toString();
					}
				}
			} catch (Exception e) {
				BaseLogger.log("1", null, null, "Error while preparing WhatsApp config :: " + e.getMessage());
				throw new ITMException(e);
			}

			BaseLogger.log("3", null, null, "WhatsApp Config (After) ::: [" + whatsappConfig + "]");

			// Send WhatsApp
			WhatsAppComm whatsAppComm = new WhatsAppComm();
	          BaseLogger.log("3", null, null, "WhatsAppComm.sendWhatsApp::  mailXMLStr" + mailXMLStr.toString());

	          BaseLogger.log("3", null, null, "WhatsAppComm.sendWhatsApp::  tranXmlString" + tranXmlString.toString());
			whatsAppComm.sendWhatsApp(templateCode, whatsappConfig, toAddress, userInfo,mailXMLStr, tranXmlString);

			// Log communication
			e12GenericUtility.writeCommunicationLog(userInfo, false, "W", "S", "WhatsApp sent successfully", toAddress,
					this.ccAddr, this.bccAddr, this.subject, templateCode, 0, null);

			return "S";
		}
		//Added by Amol S  on 15-may-25 to parse the DOMand extract the value-End
		//Amol -strt
		else if("B".equalsIgnoreCase(msgType))
		{
			BaseLogger.log("3", null, null, "Inside the B block ");
			
			sendEmailAndSms(templateCode,mailXMLStr, userInfo);
		    return "S";
		}
		
		//Added by Amol S on 13-Jun-25 to send email,sms,whstaappMsg simeltenously
		// Added by Amol S on 13-Jun-25 to send Email, SMS, WhatsApp Msg simultaneously -Start
		else if ("A".equalsIgnoreCase(msgType)) {
		    BaseLogger.log("3", null, null, "Inside the A block - sending Email, SMS, and WhatsApp");

		    sendEmailAndSmsNdWhtsApp(templateCode, mailXMLStr, userInfo);
		    BaseLogger.log("3", null, null, "Method called============>>");
 
		    return "S";
		    
		}
		// Added by Amol S on 13-Jun-25 to send Email, SMS, WhatsApp Msg simultaneously -End
		else {
			//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start

			try
			{
				String smtpServerStatus = "";
				String smtpFallback = ""; // Added by Gagan B.
				if( userInfo != null )
				{
					DBAccessEJB dbAccessEJB = new DBAccessEJB();
					smtpServerStatus = dbAccessEJB.getDBColumnValue("ENTERPRISE", " SMTP_SERVER_STATUS", "ENTERPRISE  = '"+userInfo.getEnterprise()+"'", userInfo.getTransDB());
					// Added by Gagan B for getting SMTP_FALLBACK value from ENTERPRISE table. [START]
					smtpFallback = dbAccessEJB.getDBColumnValue("ENTERPRISE", " SMTP_FALLBACK", "ENTERPRISE  = '"+userInfo.getEnterprise()+"'", userInfo.getTransDB());
					// Added by Gagan B for getting SMTP_FALLBACK value from ENTERPRISE table. [END]
				}
				BaseLogger.log("3", userInfo, null, "EMail.sendMail() smtpServerStatus:["+smtpServerStatus+"]");
				if( userInfo != null && E12GenericUtility.checkNull(userInfo.getSmtpHost()).length() > 0 && !("INVALID_STATE".equalsIgnoreCase(E12GenericUtility.checkNull(smtpServerStatus))) )
				{
					return sendMailUsingSMTP(mailXMLStr, infoType, userInfo);
				}
				else
				{
					// Added by Gagan B. to add SMTP_FALLBACK configuration on 28-JUL-22. -- START
					if(!smtpFallback.equalsIgnoreCase("Y"))
					{
						e12GenericUtility.writeCommunicationLog(userInfo, false, "E", "F", "Your SMTP configuration seems to be in invalid state and you have not configured SMTP Fallback with us!", this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, 0, null);
						return "Value of SMTP_FALLBACK is not Y.";
					}
					// Added by Gagan B. to add SMTP_FALLBACK configuration on 28-JUL-22. -- END
					return sendMailUsingIBASE(mailXMLStr, infoType, userInfo);
				}
			}
			catch (Exception e)
			{
				throw e;
			}
		}

		
		
	}
	//Added overriden methon by Ajit on 12-JAN-26 [START]
	
	
	//Added by Amol S on 14-may - 25 --start
	private DBAccessEJB getDBAccess() {
		try {
			if (dbAccess == null) {

				dbAccess = new DBAccessEJB();
			}
		}

		catch (Exception e) {
			e.printStackTrace();
		}

		return dbAccess;
	}
	//Added by Amol S on 14-may - 25 --End
	
	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
	public String sendMailUsingIBASE(String mailXMLStr, String infoType, UserInfoBean userInfo)throws Exception
	{
		BaseLogger.log("3", userInfo, null, "UserInfo in Email sendMail sendMailUsingIBASE :["+userInfo+"]");
		BaseLogger.log("3", userInfo, null, "mailXMLStr in Email sendMail sendMailUsingIBASE :["+mailXMLStr+"]");
		BaseLogger.log("3", userInfo, null, "infoType in Email sendMail sendMailUsingIBASE :["+infoType+"]");
        E12GenericUtility e12GenericUtility = new E12GenericUtility(); //Added by Samruddhi for email logging 20/05/2021
		boolean debug = false;
		boolean success = false;

		File createdFileObj = null;
		//Added By Prasahnt Chavan 03-Sep-15 [Request ID B15ESUN001]
		ArrayList<File> attachmentList = new ArrayList<File>();
		try
		{
			ibase.utility.MailInfo mailInfo = null;
			//vikrant 27/03/2006
			if ("ITM".equalsIgnoreCase(infoType))
			{
				Class mailInfoClass = Class.forName( "ibase.webitm.utility.ITMMailInfo" );
				mailInfo = ( ibase.utility.MailInfo ) mailInfoClass.newInstance();
			}
			else
			{
				mailInfo = new ibase.utility.MailInfo();
			}
			mailInfo.setMailProp(mailXMLStr, userInfo);

			StringTokenizer st_to = null;
			StringTokenizer st_cc = null;
			StringTokenizer st_bcc = null;

			//getThe to, cc and bcc addresses and pass it to st of corresponding
			this.toAddr = mailInfo.getToAddr();
			this.ccAddr = mailInfo.getCcAddr();
			this.bccAddr = mailInfo.getBccAddr();
			this.subject = mailInfo.getSubject();
			this.message =  mailInfo.getMessage();
			this.emailType =  mailInfo.getEmailType();
			//Added by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail
			this.messageType = mailInfo.getMessageType();
			//Added by Samadhan[S16FKAT002] on 23/03/2017 for send inline images in body mail
			this.inlineImages = mailInfo.getInlineImages();

			//Added by Gulzar/Gaurav Singh on 29-05-14 to set the mail_from received from mailInfoStr
			this.mailFrom = mailInfo.getMailFrom();

			/* //Danish Tuesday, June 13, 2006
			this.objName = mailInfo.getObjName();
			this.refSer = mailInfo.getRefSer();
			//this.refID = mailInfo.getRefID();
			//this.lineNo = mailInfo.getLineNo(); //Danish Tuesday, June 13, 2006*/
			this.xmlDataFilePath = mailInfo.getXmlDataFilePath();
			InternetAddress[] toaddress = null;
			InternetAddress[] ccaddress = null;
			InternetAddress[] bccaddress = null;
			//Added by Gaurav Singh on 29-05-14
			InternetAddress from = null;

			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | Start ]
			//CommonConstants.setIBASEHOME();
			if(CommonConstants.TOMCAT_HOME == null || CommonConstants.TOMCAT_HOME.trim().length() == 0)
			{
				CommonConstants.setIBASEHOME();
			}
			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | End ]

			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
			/*Properties props= new Properties();
			props.put("mail.smtp.host", CommonConstants.SMTPHOST);

			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :START
			if(CommonConstants.SMTPPORT != null && CommonConstants.SMTPPORT.trim().length() > 0)
			{
				props.put("mail.smtp.port", CommonConstants.SMTPPORT);
			}
			if(CommonConstants.PROTOCOL_TYPE != null && "SSL".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			}
			else if(CommonConstants.PROTOCOL_TYPE != null && "TLS".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.starttls.enable", "true");
			}*/
			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :END
			
			Session session = null;
			if ( CommonConstants.smtpSessions != null && CommonConstants.smtpSessions.get( CommonConstants.USERNAME ) != null )
			{
				//Changed by Prasad R on 16/12/2020 [set global credentials value while set session from smtpSessions]
				BaseLogger.log( "3", null, null, "set session from existing smtpSessions" );
				username = CommonConstants.USERNAME;
				password = CommonConstants.PASSWORD;
				session = CommonConstants.smtpSessions.get( CommonConstants.USERNAME );
				BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
			}
			else
			{
				Properties props = createIbaseMailServerProperties();
				Authenticator auth = null;
				if( CommonConstants.USERNAME != null && CommonConstants.PASSWORD != null )
				{
					props.put("mail.smtp.auth","true");
					//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
					//auth = new SMTPAuthenticator(null, false);
					auth = new SMTPAuthenticator();
					username = CommonConstants.USERNAME;
					password = CommonConstants.PASSWORD;
					BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
				}
				BaseLogger.log( "3", null, null, "props : ["+ props +"]" );
				session = Session.getInstance(props,auth);
				if ( CommonConstants.smtpSessions == null )
				{
					CommonConstants.smtpSessions = new HashMap<String, Session>();
				}
				CommonConstants.smtpSessions.put( CommonConstants.USERNAME, session );
			}
			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END

			session.setDebug(debug);
			//create message
			MimeMessage msg = new MimeMessage(session);

			//Commented and changes made by Gaurav Singh on 29-05-14 [ Start ]
			//To set the sender id dynamically. If found will set otherwise will set from CommonConstant.MAILFROM
			//InternetAddress from = new InternetAddress(CommonConstants.MAILFROM);
			
			BaseLogger.log( "3", null, null, "this.mailFrom sendMailUsingIBASE : ["+ this.mailFrom +"]" );

			if(this.mailFrom != null && this.mailFrom.trim().length() > 0)
		    {
			   BaseLogger.log( "3", null, null, "this.mailFrom sendMailUsingIBASE : ["+ this.mailFrom +"]" );
		       from = new InternetAddress(this.mailFrom);
		    }
		    else
		    {
		       from = new InternetAddress(CommonConstants.MAILFROM);
		    }
			//Commented and changes made by Gaurav Singh on 29-05-14 [ End ]

			msg.setFrom(from);

			if(this.toAddr != null && ! this.toAddr.trim().equals("") && ! this.toAddr.equalsIgnoreCase("null"))
			{
				st_to = new StringTokenizer(this.toAddr,",");
				toaddress = new InternetAddress[st_to.countTokens()];
				int ctr = 0;
				while(st_to.hasMoreTokens())
				{
					InternetAddress address=new InternetAddress(st_to.nextToken());
					toaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting to Recipients .........");
				msg.setRecipients(Message.RecipientType.TO,toaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: To Address :"+this.toAddr);
			}

			int ctr = 0;
			if (this.ccAddr != null && !this.ccAddr.trim().equals("") && !this.ccAddr.equalsIgnoreCase("null") )
			{
				st_cc = new StringTokenizer(this.ccAddr,",");
				ctr = 0;
				ccaddress = new InternetAddress[st_cc.countTokens()];
				while(st_cc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_cc.nextToken());
					ccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting cc Recipients .........");
				msg.setRecipients(Message.RecipientType.CC,ccaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: ccAddress :"+this.ccAddr);
			}

			if (this.bccAddr != null && !this.bccAddr.trim().equals("") && !this.bccAddr.equalsIgnoreCase("null") )
			{
				st_bcc = new StringTokenizer(this.bccAddr,",");
				ctr = 0;
				bccaddress=new InternetAddress[st_bcc.countTokens()];
				while(st_bcc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_bcc.nextToken());
					bccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting bcc Recipients .........");
				msg.setRecipients(Message.RecipientType.BCC,bccaddress);
			}
			else //vikrant 27/03/2006
			{
				BaseLogger.log("3",null,null,"Warning: bccAddress :"+this.bccAddr);
			}

			//Message Properties Setting
			//vikrant 27/03/2006
			if(this.subject!=null && !this.subject.trim().equalsIgnoreCase("null"))
			{
				msg.setSubject(subject);
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: Subject Not Defined !!!");
			}
			msg.setSentDate(new Date());

			//Message Body Creation
			BodyPart messageBody = new MimeBodyPart();
			BodyPart msgBodyForPage = null;
			BodyPart msgBodyForLink = null;
			Multipart multipart = new MimeMultipart();
			
			//GSB image sending part a&c for future reference
//			Multipart multipart = new MimeMultipart("related");
			
			/*
	        MimeBodyPart htmlPart = new MimeBodyPart();
	        String htmlContent = this.message;
	        
	     // Extract all Base64 image data from the HTML
	        List<String> base64ImageDataList = extractBase64ImageDataList(htmlContent);
			BaseLogger.log("3",null,null,"base64ImageDataList [" + base64ImageDataList +"]");

	        List<String> cids = new ArrayList<>();
	        int imageCounter = 1;

	        for (String base64ImageData : base64ImageDataList) {
				BaseLogger.log("3",null,null,"Inisde base64ImageData [" + base64ImageData +"]");

	            String cid = "base64Image" + imageCounter++;
	            cids.add(cid);

	            // Decode each Base64 image
	            byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);

	            // Create image part for each Base64 image
	            MimeBodyPart base64ImagePart = new MimeBodyPart();
	            DataSource imageDataSource = new ByteArrayDataSource(new ByteArrayInputStream(imageBytes), "image/png"); // Adjust image type if necessary
	            base64ImagePart.setDataHandler(new DataHandler(imageDataSource));
	            base64ImagePart.setHeader("Content-ID", "<" + cid + ">");
	            base64ImagePart.setDisposition(MimeBodyPart.INLINE);

	            // Add the Base64 image part to the multipart message
	            multipart.addBodyPart(base64ImagePart);
	        }

	        // Replace Base64 images in HTML with cid references
	        if (!cids.isEmpty()) {
	            htmlContent = replaceBase64WithCid(htmlContent, cids);
	        }

	        // Add the HTML content to the email body
	        htmlPart.setContent(htmlContent, "text/html");
	        multipart.addBodyPart(htmlPart);
	        GSB image sending part a&c for future reference
	        */

			//part one: text message
			//vikrant 27/03/2006
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]Start
			/*if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
			{
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail start.
				//messageBody.setText(this.message);
				BaseLogger.log("9",null,null,"this.messageType:"+this.messageType);
				if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
				{
					messageBody.setContent(this.message, this.messageType);
				}else
				{
					messageBody.setText(this.message);
				}
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail end.
			}
			else
			{
				BaseLogger.log("9",null,null,"Warning: Message Not Defined !!!");
				messageBody.setText("");
			}
			multipart.addBodyPart(messageBody);*/
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]End
			//Samadhan
			
//			String body = "Hello";
//			this.message = "<html><body>" + body + "<br><img src=\"cid:IMAGE1\"><br><img src=\"cid:IMAGE2\"></body></html>";
			/*
			 * Added by Gagan B. on 07-OCT-24 for handling images in the HTML
			 * replacing base64 content with cid to resolve image rendering issues in Gmail-- START
			 * */
			// Extract all Base64 image data from the HTML
	        List<String> base64ImageDataList = extractBase64ImageDataList(this.message);
			BaseLogger.log("3",null,null,"base64ImageDataList [" + base64ImageDataList +"]");

	        List<String> cids = new ArrayList<>();
	        int imageCounter = 1;
	        
	        if (base64ImageDataList != null || !base64ImageDataList.isEmpty()) {
	        	for (String base64ImageData : base64ImageDataList) {
					BaseLogger.log("3",null,null,"Inisde base64ImageData [" + base64ImageData +"]");

		            String cid = "base64Image" + imageCounter++;
		            cids.add(cid);

		            // Decode each Base64 image
		            byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);

		            // Create image part for each Base64 image
		            MimeBodyPart base64ImagePart = new MimeBodyPart();
		            DataSource imageDataSource = new ByteArrayDataSource(new ByteArrayInputStream(imageBytes), "image/png"); // Adjust image type if necessary
		            base64ImagePart.setDataHandler(new DataHandler(imageDataSource));
		            base64ImagePart.setHeader("Content-ID", "<" + cid + ">");
		            base64ImagePart.setDisposition(MimeBodyPart.INLINE);

		            // Add the Base64 image part to the multipart message
		            multipart.addBodyPart(base64ImagePart);
		        }
	        }

	        // Replace Base64 images in HTML with cid references
	        if (cids != null || !cids.isEmpty()) {
	            this.message = replaceBase64WithCid(this.message, cids);
	        }
	        /*
			 * Added by Gagan B. on 07-OCT-24 for handling images in the HTML
			 * replacing base64 content with cid to resolve image rendering issues in Gmail-- END
			 * */
	        
			if(inlineImages != null)
			{
				for (String key : inlineImages.keySet())
				{
					MimeBodyPart messageBodyPart1 = new MimeBodyPart();
					DataSource fds = new FileDataSource(inlineImages.get(key));
					messageBodyPart1.setDataHandler(new DataHandler(fds));
					messageBodyPart1.setHeader("Content-ID", "<"+key+">");
					multipart.addBodyPart(messageBodyPart1);
					BaseLogger.log("3",null,null,"inline path:"+inlineImages.get(key));
				}
			}
			
			//part two: attachment
			//vikrant 27/03/2006
			if (this.emailType != null && this.emailType.trim().length() > 0 && !this.emailType.trim().equalsIgnoreCase("null"))
			{
				if(this.emailType.equals("page"))
				{
					//vikrant 27/03/2006
					if (this.xmlDataFilePath != null)
					{
						//Changed By Prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] Start
						/*createdFileObj = new File(this.xmlDataFilePath);
						msgBodyForPage = new MimeBodyPart();
						DataSource source = new FileDataSource(createdFileObj);
						msgBodyForPage.setDataHandler(new DataHandler(source));
						BaseLogger.log("9",null,null,createdFileObj);

						//Changed by Gulzar on 07/11/14 - START
						//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
						}
						else
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						}
						//Changed by Gulzar on 07/11/14 - END
						BaseLogger.log("9",null,null,"File name :"+msgBodyForPage.getFileName()+":");
						multipart.addBodyPart(msgBodyForPage);*/
						if(this.xmlDataFilePath.indexOf(";") != -1)
						{
							BaseLogger.log("3",null,null,"xmlDataFilePath"+this.xmlDataFilePath);
							String[] dataFilePathArry = this.xmlDataFilePath.split(";");
							BaseLogger.log("3",null,null,"dataFilePathArry length [ "+dataFilePathArry.length+" ]");
							for(int i = 0; i < dataFilePathArry.length; i++)
							{
								createdFileObj = new File(dataFilePathArry[i]);
								msgBodyForPage = new MimeBodyPart();
								DataSource source = new FileDataSource(createdFileObj);
								msgBodyForPage.setDataHandler(new DataHandler(source));
								BaseLogger.log("3",null,null,createdFileObj);

								//Changed by Gulzar on 07/11/14 - START
								//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
								}
								else
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								}
								//Changed by Gulzar on 07/11/14 - END
								BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
								multipart.addBodyPart(msgBodyForPage);
								//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
								attachmentList.add(createdFileObj);
							}
						}
						else
						{
							createdFileObj = new File(this.xmlDataFilePath);
							msgBodyForPage = new MimeBodyPart();
							DataSource source = new FileDataSource(createdFileObj);
							msgBodyForPage.setDataHandler(new DataHandler(source));
							BaseLogger.log("3",null,null,createdFileObj);

							//Changed by Gulzar on 07/11/14 - START
							//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
							}
							else
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							}
							//Changed by Gulzar on 07/11/14 - END
							BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
							multipart.addBodyPart(msgBodyForPage);
							//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
							attachmentList.add(createdFileObj);
						}
						//Added By prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] End
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: xmlDataFilePath :"+xmlDataFilePath);
					}
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][Start]
					if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
					{
						BaseLogger.log("3",null,null,"line no:441...this.messageType:"+this.messageType);
						if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
						{
							messageBody.setContent(this.message, this.messageType);
						}else
						{
							messageBody.setText(this.message);
						}
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
						messageBody.setText("");
					}
					multipart.addBodyPart(messageBody);
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][End]
				}
				if(this.emailType.equals("link"))
				{
					//createdFileObj = mailInfo.getLinkFileObj(this.objName, this.refSer,  this.refID, this.lineNo); //builds the link to be send  //Danish Tuesday, June 13, 2006
					//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]
					createdFileObj = mailInfo.getLinkFileObj( this.message ); //builds the link to be send
					msgBodyForLink = new MimeBodyPart();
					DataSource source = new FileDataSource(createdFileObj);
					msgBodyForLink.setDataHandler(new DataHandler(source));
					BaseLogger.log("3",null,null,"FileObjCreated ..."+ createdFileObj);
					multipart.addBodyPart(msgBodyForLink);
					//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
					attachmentList.add(createdFileObj);
				}
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: emailType not found !!!");
				//Changed by Anjali R.[10/09/2017][Start][For bug fixing in system generated emails]
				if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
				{
					BaseLogger.log("3",null,null,"this.messageType:"+this.messageType);
					if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
					{
						messageBody.setContent(this.message, this.messageType);
					}
					else
					{
						if(this.message.toLowerCase().indexOf("<html>") != -1)
						{
							messageBody.setContent(this.message, "text/html; charset=utf-8");
						}
						else
						{
							messageBody.setText(this.message);
						}
					}
				}
				else
				{
					BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
					messageBody.setText("");
				}
				multipart.addBodyPart(messageBody);
				//Changed by Anjali R.[10/09/2017][End][For bug fixing in system generated emails]
			}
			msg.setContent(multipart);// Put parts in message
			BaseLogger.log("3",null,null,"[EMail]Sending Mail..............................");
			if(msg.getRecipients(Message.RecipientType.TO) != null || msg.getRecipients(Message.RecipientType.CC) != null || msg.getRecipients(Message.RecipientType.BCC) != null)
			{
				Transport.send(msg);
                //Added by Samruddhi for email logging on 20/05/2021
				if (this.message.length() > 1500) {
					this.message = this.message.substring(0, 1500);
				}
                e12GenericUtility.writeCommunicationLog(userInfo, false, "E", "S", "Mail send successfully", this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, attachmentList.size(), attachmentList);
                BaseLogger.log("3", null, null, "EMail.sendMailUsingIBASE() objName : [" + mailInfo.getObjName() + "]");
                BaseLogger.log("3", null, null, "EMail.sendMailUsingIBASE() refId   : [" + mailInfo.getRefID() + "]");
                if( userInfo != null && mailInfo.getObjName() != null && mailInfo.getRefID() != null )
                {
                	updateTransactionMailStatus(mailInfo.getObjName(), mailInfo.getRefID(), userInfo);
                }
			}

			BaseLogger.log("3",null,null,"[EMail]Message Sent ...");
			//Changed by Prashant Chavan on 04-Sep-15 for deleting the Multiple Attachments Start
			/*if(createdFileObj!= null)
			{
				createdFileObj.delete(); //deleting the temp file
			}*/
			if( attachmentList.size() > 0)
			{
				for(int i = 0;i < attachmentList.size(); i++)
				{
					File attachmentFileObj = attachmentList.get(i);
					attachmentFileObj.delete();
				}
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception :EMail :sendMail :==>\n["+ E12GenericUtility.getStackTrace(e) + "]");
			e.printStackTrace();
			//Added by Samruddhi for email logging on 20/05/2021 [Start]
            //ITMException ie = new ITMException(e);
            //String errStr = ie.getMessage();
			String errStr = E12GenericUtility.getStackTrace(e);
            int errStrLen = errStr.length();
            
            if(errStr.contains("In Mail sending TO_ADD is null"))
            {
            	errStr = "To Address is not specified";
            }
            else if(errStrLen > 4000)
            {
                errStr = errStr.substring(0,4000);
            }
            if (this.message.length() > 1500) {
				this.message = this.message.substring(0, 1500);
			}
            e12GenericUtility.writeCommunicationLog(userInfo, true, "E", "F", errStr, this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, attachmentList.size(), attachmentList);
            //Added by Samruddhi for email logging on 20/05/2021 [End]
			throw e;
		}
		return "S";
	}
	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end

	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
	public String sendMailUsingSMTP(String mailXMLStr, String infoType, UserInfoBean userInfo)throws Exception
	{
		BaseLogger.log( "3", userInfo, null, "UserInfo in sendMailUsingSMTP :: Email sendMail : ["+userInfo+"]" );
        E12GenericUtility e12GenericUtility = new E12GenericUtility(); //Added by Samruddhi for email logging 20/05/2021
		boolean debug = false;
		boolean success = false;

		File createdFileObj = null;
		//Added By Prasahnt Chavan 03-Sep-15 [Request ID B15ESUN001]
		ArrayList<File> attachmentList = new ArrayList<File>();
		try
		{
			ibase.utility.MailInfo mailInfo = null;
			//vikrant 27/03/2006
			if ("ITM".equalsIgnoreCase(infoType))
			{
				Class mailInfoClass = Class.forName( "ibase.webitm.utility.ITMMailInfo" );
				mailInfo = ( ibase.utility.MailInfo ) mailInfoClass.newInstance();
			}
			else
			{
				mailInfo = new ibase.utility.MailInfo();
			}
			mailInfo.setMailProp(mailXMLStr, userInfo);

			StringTokenizer st_to = null;
			StringTokenizer st_cc = null;
			StringTokenizer st_bcc = null;

			//getThe to, cc and bcc addresses and pass it to st of corresponding
			this.toAddr = mailInfo.getToAddr();
			this.ccAddr = mailInfo.getCcAddr();
			this.bccAddr = mailInfo.getBccAddr();
			this.subject = mailInfo.getSubject();
			this.message =  mailInfo.getMessage();
			this.emailType =  mailInfo.getEmailType();
			//Added by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail
			this.messageType = mailInfo.getMessageType();
			//Added by Samadhan[S16FKAT002] on 23/03/2017 for send inline images in body mail
			this.inlineImages = mailInfo.getInlineImages();

			//Added by Gulzar/Gaurav Singh on 29-05-14 to set the mail_from received from mailInfoStr
			this.mailFrom = mailInfo.getMailFrom();

			/* //Danish Tuesday, June 13, 2006
			this.objName = mailInfo.getObjName();
			this.refSer = mailInfo.getRefSer();
			//this.refID = mailInfo.getRefID();
			//this.lineNo = mailInfo.getLineNo(); //Danish Tuesday, June 13, 2006*/
			this.xmlDataFilePath = mailInfo.getXmlDataFilePath();
			InternetAddress[] toaddress = null;
			InternetAddress[] ccaddress = null;
			InternetAddress[] bccaddress = null;
			//Added by Gaurav Singh on 29-05-14
			InternetAddress from = null;

			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | Start ]
			//CommonConstants.setIBASEHOME();
			if(CommonConstants.TOMCAT_HOME == null || CommonConstants.TOMCAT_HOME.trim().length() == 0)
			{
				CommonConstants.setIBASEHOME();
			}
			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | End ]
			
			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
			Session session = null;
			if ( CommonConstants.smtpSessions != null && CommonConstants.smtpSessions.get( userInfo.getSmtpUser() ) != null )
			{
				//Changed by Prasad R on 16/12/2020 [set global credentials value while set session from smtpSessions]
				BaseLogger.log( "3", null, null, "set session from existing smtpSessions" );
				username = userInfo.getSmtpUser();
				password = userInfo.getSmtpPassWD();
				session = CommonConstants.smtpSessions.get( userInfo.getSmtpUser() );
				BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
			}
			else
			{
				Properties props = createSMTPServerProperties(userInfo);
				Authenticator auth = null;
				if( userInfo.getSmtpUser() != null && userInfo.getSmtpPassWD() != null )
				{
					props.put("mail.smtp.auth","true");
					//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
					//auth = new SMTPAuthenticator(null, false);
					auth = new SMTPAuthenticator();
					username = userInfo.getSmtpUser();
					password = userInfo.getSmtpPassWD();
					BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
				}
				BaseLogger.log( "3", null, null, "props : ["+ props +"]" );
				session = Session.getInstance(props,auth);
				if ( CommonConstants.smtpSessions == null )
				{
					CommonConstants.smtpSessions = new HashMap<String, Session>();
				}
				CommonConstants.smtpSessions.put( userInfo.getSmtpUser(), session );
			}
			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END
			
			session.setDebug(debug);
			//create message
			MimeMessage msg = new MimeMessage(session);

			//Commented and changes made by Gaurav Singh on 29-05-14 [ Start ]
			//To set the sender id dynamically. If found will set otherwise will set from CommonConstant.MAILFROM
			//InternetAddress from = new InternetAddress(CommonConstants.MAILFROM);
			if( userInfo !=  null && E12GenericUtility.checkNull(userInfo.getSmtpHost()).length() > 0 && E12GenericUtility.checkNull(userInfo.getSmtpMailFrom()).length() > 0 )
			{
				from = new InternetAddress(userInfo.getSmtpMailFrom());
			}
			else
			{
				if(this.mailFrom != null && this.mailFrom.trim().length() > 0)
				{
					from = new InternetAddress(this.mailFrom);
				}
				else
				{
					from = new InternetAddress(CommonConstants.MAILFROM);
				}
			}
			//Commented and changes made by Gaurav Singh on 29-05-14 [ End ]

			msg.setFrom(from);

			if(this.toAddr != null && ! this.toAddr.trim().equals("") && ! this.toAddr.equalsIgnoreCase("null"))
			{
				st_to = new StringTokenizer(this.toAddr,",");
				toaddress = new InternetAddress[st_to.countTokens()];
				int ctr = 0;
				while(st_to.hasMoreTokens())
				{
					InternetAddress address=new InternetAddress(st_to.nextToken());
					toaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting to Recipients .........");
				msg.setRecipients(Message.RecipientType.TO,toaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: To Address :"+this.toAddr);
			}

			int ctr = 0;
			if (this.ccAddr != null && !this.ccAddr.trim().equals("") && !this.ccAddr.equalsIgnoreCase("null") )
			{
				st_cc = new StringTokenizer(this.ccAddr,",");
				ctr = 0;
				ccaddress = new InternetAddress[st_cc.countTokens()];
				while(st_cc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_cc.nextToken());
					ccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting cc Recipients .........");
				msg.setRecipients(Message.RecipientType.CC,ccaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: ccAddress :"+this.ccAddr);
			}

			if (this.bccAddr != null && !this.bccAddr.trim().equals("") && !this.bccAddr.equalsIgnoreCase("null") )
			{
				st_bcc = new StringTokenizer(this.bccAddr,",");
				ctr = 0;
				bccaddress=new InternetAddress[st_bcc.countTokens()];
				while(st_bcc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_bcc.nextToken());
					bccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting bcc Recipients .........");
				msg.setRecipients(Message.RecipientType.BCC,bccaddress);
			}
			else //vikrant 27/03/2006
			{
				BaseLogger.log("3",null,null,"Warning: bccAddress :"+this.bccAddr);
			}

			//Message Properties Setting
			//vikrant 27/03/2006
			if(this.subject!=null && !this.subject.trim().equalsIgnoreCase("null"))
			{
				msg.setSubject(subject);
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: Subject Not Defined !!!");
			}
			msg.setSentDate(new Date());

			//Message Body Creation
			BodyPart messageBody = new MimeBodyPart();
			BodyPart msgBodyForPage = null;
			BodyPart msgBodyForLink = null;
			Multipart multipart = new MimeMultipart();

			//part one: text message
			//vikrant 27/03/2006
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]Start
			/*if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
			{
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail start.
				//messageBody.setText(this.message);
				BaseLogger.log("9",null,null,"this.messageType:"+this.messageType);
				if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
				{
					messageBody.setContent(this.message, this.messageType);
				}else
				{
					messageBody.setText(this.message);
				}
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail end.
			}
			else
			{
				BaseLogger.log("9",null,null,"Warning: Message Not Defined !!!");
				messageBody.setText("");
			}
			multipart.addBodyPart(messageBody);*/
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]End
			//Samadhan
			
			/*
			// GSB23SEP24
			List<String> base64ImageDataList = extractBase64ImageDataList(this.message);
			List<String> cids = new ArrayList<>();
			int imageCounter = 1;
			
			for (String base64ImageData : base64ImageDataList) {
	            String cid = "base64Image" + imageCounter++;
	            cids.add(cid);

	            // Decode each Base64 image
	            byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);

	            // Create image part for each Base64 image
	            MimeBodyPart base64ImagePart = new MimeBodyPart();
	            DataSource imageDataSource = new ByteArrayDataSource(new ByteArrayInputStream(imageBytes), "image/png"); // Adjust image type if necessary
	            base64ImagePart.setDataHandler(new DataHandler(imageDataSource));
	            base64ImagePart.setHeader("Content-ID", "<" + cid + ">");
	            base64ImagePart.setDisposition(MimeBodyPart.INLINE);

	            // Add the Base64 image part to the multipart message
	            multipart.addBodyPart(base64ImagePart);
				BaseLogger.log("3",null,null,"multipart base64ImageData[" + multipart + "]");

	        }

	        // Replace Base64 images in HTML with cid references
	        if (!cids.isEmpty()) {
	            this.message = replaceBase64WithCid(this.message, cids);
	        }
	        */
			
			/*
			 * Added by Gagan B. on 11-OCT-24 for handling images in the HTML
			 * replacing base64 content with cid to resolve image rendering issues in Gmail-- START
			 * */
			// Extract all Base64 image data from the HTML
	        List<String> base64ImageDataList = extractBase64ImageDataList(this.message);
			BaseLogger.log("3",null,null,"base64ImageDataList [" + base64ImageDataList +"]");

	        List<String> cids = new ArrayList<>();
	        int imageCounter = 1;
	        
	        if (base64ImageDataList != null || !base64ImageDataList.isEmpty()) {
	        	for (String base64ImageData : base64ImageDataList) {
					BaseLogger.log("3",null,null,"Inisde base64ImageData [" + base64ImageData +"]");

		            String cid = "base64Image" + imageCounter++;
		            cids.add(cid);

		            // Decode each Base64 image
		            byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);

		            // Create image part for each Base64 image
		            MimeBodyPart base64ImagePart = new MimeBodyPart();
		            DataSource imageDataSource = new ByteArrayDataSource(new ByteArrayInputStream(imageBytes), "image/png"); // Adjust image type if necessary
		            base64ImagePart.setDataHandler(new DataHandler(imageDataSource));
		            base64ImagePart.setHeader("Content-ID", "<" + cid + ">");
		            base64ImagePart.setDisposition(MimeBodyPart.INLINE);

		            // Add the Base64 image part to the multipart message
		            multipart.addBodyPart(base64ImagePart);
		        }
	        }

	        // Replace Base64 images in HTML with cid references
	        if (cids != null || !cids.isEmpty()) {
	            this.message = replaceBase64WithCid(this.message, cids);
	        }
	        /*
			 * Added by Gagan B. on 11-OCT-24 for handling images in the HTML
			 * replacing base64 content with cid to resolve image rendering issues in Gmail-- END
			 * */
			
			if(inlineImages != null)
			{
				for (String key : inlineImages.keySet())
				{
					MimeBodyPart messageBodyPart1 = new MimeBodyPart();
					DataSource fds = new FileDataSource(inlineImages.get(key));
					messageBodyPart1.setDataHandler(new DataHandler(fds));
					messageBodyPart1.setHeader("Content-ID", "<"+key+">");
					multipart.addBodyPart(messageBodyPart1);
					BaseLogger.log("3",null,null,"inline path:"+inlineImages.get(key));
				}
			}
			//part two: attachment
			//vikrant 27/03/2006
			if (this.emailType != null && this.emailType.trim().length() > 0 && !this.emailType.trim().equalsIgnoreCase("null"))
			{
				if(this.emailType.equals("page"))
				{
					//vikrant 27/03/2006
					if (this.xmlDataFilePath != null)
					{
						//Changed By Prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] Start
						/*createdFileObj = new File(this.xmlDataFilePath);
						msgBodyForPage = new MimeBodyPart();
						DataSource source = new FileDataSource(createdFileObj);
						msgBodyForPage.setDataHandler(new DataHandler(source));
						BaseLogger.log("9",null,null,createdFileObj);

						//Changed by Gulzar on 07/11/14 - START
						//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
						}
						else
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						}
						//Changed by Gulzar on 07/11/14 - END
						BaseLogger.log("9",null,null,"File name :"+msgBodyForPage.getFileName()+":");
						multipart.addBodyPart(msgBodyForPage);*/
						if(this.xmlDataFilePath.indexOf(";") != -1)
						{
							BaseLogger.log("3",null,null,"xmlDataFilePath"+this.xmlDataFilePath);
							String[] dataFilePathArry = this.xmlDataFilePath.split(";");
							BaseLogger.log("3",null,null,"dataFilePathArry length [ "+dataFilePathArry.length+" ]");
							for(int i = 0; i < dataFilePathArry.length; i++)
							{
								createdFileObj = new File(dataFilePathArry[i]);
								msgBodyForPage = new MimeBodyPart();
								DataSource source = new FileDataSource(createdFileObj);
								msgBodyForPage.setDataHandler(new DataHandler(source));
								BaseLogger.log("3",null,null,createdFileObj);

								//Changed by Gulzar on 07/11/14 - START
								//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
								}
								else
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								}
								//Changed by Gulzar on 07/11/14 - END
								BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
								multipart.addBodyPart(msgBodyForPage);
								//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
								attachmentList.add(createdFileObj);
							}
						}
						else
						{
							createdFileObj = new File(this.xmlDataFilePath);
							msgBodyForPage = new MimeBodyPart();
							DataSource source = new FileDataSource(createdFileObj);
							msgBodyForPage.setDataHandler(new DataHandler(source));
							BaseLogger.log("3",null,null,createdFileObj);

							//Changed by Gulzar on 07/11/14 - START
							//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
							}
							else
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							}
							//Changed by Gulzar on 07/11/14 - END
							BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
							multipart.addBodyPart(msgBodyForPage);
							//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
							attachmentList.add(createdFileObj);
						}
						//Added By prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] End
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: xmlDataFilePath :"+xmlDataFilePath);
					}
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][Start]
					if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
					{
						BaseLogger.log("3",null,null,"line no:441...this.messageType:"+this.messageType);
						if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
						{
							messageBody.setContent(this.message, this.messageType);
						}else
						{
							messageBody.setText(this.message);
						}
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
						messageBody.setText("");
					}
					multipart.addBodyPart(messageBody);
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][End]
				}
				if(this.emailType.equals("link"))
				{
					//createdFileObj = mailInfo.getLinkFileObj(this.objName, this.refSer,  this.refID, this.lineNo); //builds the link to be send  //Danish Tuesday, June 13, 2006
					//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]
					createdFileObj = mailInfo.getLinkFileObj( this.message ); //builds the link to be send
					msgBodyForLink = new MimeBodyPart();
					DataSource source = new FileDataSource(createdFileObj);
					msgBodyForLink.setDataHandler(new DataHandler(source));
					BaseLogger.log("3",null,null,"FileObjCreated ..."+ createdFileObj);
					multipart.addBodyPart(msgBodyForLink);
					//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
					attachmentList.add(createdFileObj);
				}
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: emailType not found !!!");
				//Changed by Anjali R.[10/09/2017][Start][For bug fixing in system generated emails]
				if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
				{
					BaseLogger.log("3",null,null,"this.messageType:"+this.messageType);
					if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
					{
						messageBody.setContent(this.message, this.messageType);
					}
					else
					{
						if(this.message.toLowerCase().indexOf("<html>") != -1)
						{
							messageBody.setContent(this.message, "text/html; charset=utf-8");
						}
						else
						{
							messageBody.setText(this.message);
						}
					}
				}
				else
				{
					BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
					messageBody.setText("");
				}
				multipart.addBodyPart(messageBody);
				//Changed by Anjali R.[10/09/2017][End][For bug fixing in system generated emails]
			}
			msg.setContent(multipart);// Put parts in message
			BaseLogger.log("3",null,null,"[EMail]Sending Mail..............................");
			if(msg.getRecipients(Message.RecipientType.TO) != null || msg.getRecipients(Message.RecipientType.CC) != null || msg.getRecipients(Message.RecipientType.BCC) != null)
			{
				Transport.send(msg);
                //Added by Samruddhi for email logging on 20/05/2021
				if (this.message.length() > 1500) {
					this.message = this.message.substring(0, 1500);
				}
                e12GenericUtility.writeCommunicationLog(userInfo, false, "E", "S", "Mail send successfully", this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, attachmentList.size(), attachmentList);
                BaseLogger.log("3", null, null, "EMail.sendMailUsingSMTP() objName : [" + mailInfo.getObjName() + "]");
                BaseLogger.log("3", null, null, "EMail.sendMailUsingSMTP() refId   : [" + mailInfo.getRefID() + "]");
                if( userInfo != null && mailInfo.getObjName() != null && mailInfo.getRefID() != null )
                {
                	updateTransactionMailStatus(mailInfo.getObjName(), mailInfo.getRefID(), userInfo);
                }
			}

			BaseLogger.log("3",null,null,"[EMail]Message Sent ...");
			//Changed by Prashant Chavan on 04-Sep-15 for deleting the Multiple Attachments Start
			/*if(createdFileObj!= null)
			{
				createdFileObj.delete(); //deleting the temp file
			}*/
			if( attachmentList.size() > 0)
			{
				for(int i = 0;i < attachmentList.size(); i++)
				{
					File attachmentFileObj = attachmentList.get(i);
					attachmentFileObj.delete();
				}
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0", userInfo, null, "Exception in EMail sendMail if block:["+E12GenericUtility.getStackTrace(e)+"]");
			
			PreparedStatement psmt = null;
			Connection conn = null;
			try
			{
				//Added by Samruddhi for email logging on 20/05/2021 [Start]
				//ITMException ie = new ITMException(e);
                //String errStr = ie.getMessage();
				String errStr = E12GenericUtility.getStackTrace(e);
                int errStrLen = errStr.length();
                
                if(errStr.contains("In Mail sending TO_ADD is null"))
                {
                	errStr = "To Address is not specified";
                }
                else if(errStrLen > 4000)
                {
                    errStr = errStr.substring(0,4000);
                }
                if (this.message.length() > 1500) {
					this.message = this.message.substring(0, 1500);
				}
				e12GenericUtility.writeCommunicationLog(userInfo, true, "E", "F", errStr, this.toAddr, this.ccAddr, this.bccAddr, this.subject, this.message, attachmentList.size(), attachmentList);
				//Added by Samruddhi for email logging on 20/05/2021 [End]
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB(userInfo.getTransDB());
				String sql = "UPDATE ENTERPRISE SET SMTP_SERVER_STATUS = 'INVALID_STATE' WHERE ENTERPRISE = '"+userInfo.getEnterprise()+"'";
				psmt = conn.prepareStatement(sql);
				int updateCount = psmt.executeUpdate();
				BaseLogger.log("2", userInfo, null, "Update Count :["+updateCount+"]");
				
				psmt.close();
				psmt = null;
				
				//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
				Session session = null;
				if ( CommonConstants.smtpSessions != null && CommonConstants.smtpSessions.get( CommonConstants.USERNAME ) != null )
				{
					//Changed by Prasad R on 16/12/2020 [set global credentials value while set session from smtpSessions]
					BaseLogger.log( "3", null, null, "set session from existing smtpSessions" );
					username = CommonConstants.USERNAME;
					password = CommonConstants.PASSWORD;
					session = CommonConstants.smtpSessions.get( CommonConstants.USERNAME );
					BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
				}
				else
				{
					Properties props = createIbaseMailServerProperties();
					Authenticator auth = null;
					if( CommonConstants.USERNAME != null && CommonConstants.PASSWORD != null )
					{
						props.put("mail.smtp.auth","true");
						//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
						//auth = new SMTPAuthenticator(null, false);
						auth = new SMTPAuthenticator();
						username = CommonConstants.USERNAME;
						password = CommonConstants.PASSWORD;
						BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
					}
					BaseLogger.log( "3", null, null, "props : ["+ props +"]" );
					
					session = Session.getInstance(props,auth);
					if ( CommonConstants.smtpSessions == null )
					{
						CommonConstants.smtpSessions = new HashMap<String, Session>();
					}
					CommonConstants.smtpSessions.put( CommonConstants.USERNAME, session );
				}
				//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END

				session.setDebug(debug);
				
				MimeMessage msg = new MimeMessage(session);
				InternetAddress from = new InternetAddress(CommonConstants.MAILFROM);
				msg.setFrom(from);
				InternetAddress[] adminAddress = null;
				if( userInfo != null && userInfo.getAdminEmailId() != null && !userInfo.getAdminEmailId().trim().equals("") && !userInfo.getAdminEmailId().equalsIgnoreCase("null"))
				{
					BaseLogger.log("3", userInfo, null, "EMail.sendMailUsingSMTP() admin emisl id:["+userInfo.getAdminEmailId()+"]");
					StringTokenizer st_to = new StringTokenizer(userInfo.getAdminEmailId(),",");
					adminAddress = new InternetAddress[st_to.countTokens()];
					int ctr = 0;
					while(st_to.hasMoreTokens())
					{
						InternetAddress address = new InternetAddress(st_to.nextToken());
						adminAddress[ctr] = address;
						ctr++;
					}
					msg.setRecipients(Message.RecipientType.TO,adminAddress);
				}
				//Added by Samruddhi for email logging on 20/05/2021
				String mailSubject = "Failed to connect SMTP mail server configured against ENTERPRISE";
				String mailBody = "Dear Sir/Madam, \n\n\t Failed to connect SMTP mail server configured against ENTERPRISE. So please rectify your SMTP mail server issue and update the status in \"SMTP SERVER STATUS\" column against ENTERPRISE in ENTERPRISE table after SMTP mail server started properly. \n\n\n Regards \n\n Proteus Team";
				String toADDR = adminAddress.toString();
				msg.setSubject(mailSubject);
				msg.setSentDate(new Date());
				
				//Message Body Creation
				BodyPart messageBody = new MimeBodyPart();
				Multipart multipart = new MimeMultipart();
				//Changed by Prasad	on 01/12/2020 [changed the \n character]
				//messageBody.setText("Dear Sir/Madam, /n/n/t Failed to connect SMTP mail server configured against ENTERPRISE. So please rectify your SMTP mail server issue and update the status in \"SMTP SERVER STATUS\" column against ENTERPRISE in ENTERPRISE table after SMTP mail server started properly. /n/n/n Regards /n/n Proteus Team");
				messageBody.setText(mailBody);
				multipart.addBodyPart(messageBody);
				msg.setContent(multipart);
				BaseLogger.log("3",null,null,"[EMail]Sending Mail To Admin..............................");
				if(msg.getRecipients(Message.RecipientType.TO) != null || msg.getRecipients(Message.RecipientType.CC) != null || msg.getRecipients(Message.RecipientType.BCC) != null)
				{
					Transport.send(msg);
					if (this.message.length() > 1500) {
						this.message = this.message.substring(0, 1500);
					}
                    //Added by Samruddhi for email logging on 20/05/2021
                    e12GenericUtility.writeCommunicationLog(userInfo, true, "E", "S", "Mail send successfully", toADDR, "", "", mailSubject, mailBody, 0, null);
				}
				BaseLogger.log("3",null,null,"[EMail]Message Sent To Admin..............................");
				//Added by Samruddhi on 04/05/2021 to check if SMTPFAILOVER value = yes then only send email using vision smtp server [Start]
                String smtpFailover = "";
                if( userInfo != null )
			    {
                    DBAccessEJB dbAccessEJB = new DBAccessEJB();
                    smtpFailover = dbAccessEJB.getDBColumnValue("ENTERPRISE", "SMTP_FAILOVER", "ENTERPRISE  = '"+userInfo.getEnterprise()+"'", userInfo.getTransDB());
                }
				if(smtpFailover != null && "Y".equalsIgnoreCase(smtpFailover))
                {
                    sendMailUsingIBASE(mailXMLStr, infoType, userInfo);
                    BaseLogger.log("3",null,null,"[EMail]Message Sent using IBASE.....................");
                }
                //Added by Samruddhi on 04/05/2021 to check if SMTPFAILOVER value = yes then only send email using vision smtp server [End]
			}
			catch (Exception e2)
			{
				BaseLogger.log("0", userInfo, null, "Exception in catch block of sending admin mail:["+E12GenericUtility.getStackTrace(e2)+"]");
				throw e2;
			}
			finally
			{
				try
				{
					conn.commit();
					if( psmt != null )
					{
						psmt.close();
						psmt = null;
					}
					if( conn != null )
					{
						conn.close();
						conn = null;
					}
				}
				catch (Exception e3)
				{
					BaseLogger.log("3", userInfo, null, "EMail.sendMailUsingSMTP() Exception in finally :["+E12GenericUtility.getStackTrace(e3)+"]");
				}
			}
		}
		return "S";
	}
	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end

	public String sendMail(String mailXMLStr, String infoType, Connection connection)throws Exception
	{
		boolean debug = false;
		boolean success = false;

		File createdFileObj = null;
		//Added By Prasahnt Chavan 03-Sep-15 [Request ID B15ESUN001]
		ArrayList<File> attachmentList = new ArrayList<File>();
		try
		{
			ibase.utility.MailInfo mailInfo = null;
			//vikrant 27/03/2006
			if ("ITM".equalsIgnoreCase(infoType))
			{
				Class mailInfoClass = Class.forName( "ibase.webitm.utility.ITMMailInfo" );
				mailInfo = ( ibase.utility.MailInfo ) mailInfoClass.newInstance();
			}
			else
			{
				mailInfo = new ibase.utility.MailInfo();
			}
			mailInfo.setMailProp(mailXMLStr, connection);

			// Added by Abhishek T on 20-June-18 [For sending notification] START
			if (mailInfo instanceof ITMMailInfo) {
				entityCodes = ((ITMMailInfo) mailInfo).getEntityCode();
			}
			// Added by Abhishek T on 20-June-18 [For sending notification] END

			StringTokenizer st_to = null;
			StringTokenizer st_cc = null;
			StringTokenizer st_bcc = null;

			//getThe to, cc and bcc addresses and pass it to st of corresponding
			this.toAddr = mailInfo.getToAddr();
			this.ccAddr = mailInfo.getCcAddr();
			this.bccAddr = mailInfo.getBccAddr();
			this.subject = mailInfo.getSubject();
			this.message =  mailInfo.getMessage();
			this.emailType =  mailInfo.getEmailType();
			//Added by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail
			this.messageType = mailInfo.getMessageType();
			//Added by Samadhan[S16FKAT002] on 23/03/2017 for send inline images in body mail
			this.inlineImages = mailInfo.getInlineImages();

			//Added by Gulzar/Gaurav Singh on 29-05-14 to set the mail_from received from mailInfoStr
			this.mailFrom = mailInfo.getMailFrom();

			/* //Danish Tuesday, June 13, 2006
			this.objName = mailInfo.getObjName();
			this.refSer = mailInfo.getRefSer();
			//this.refID = mailInfo.getRefID();
			//this.lineNo = mailInfo.getLineNo(); //Danish Tuesday, June 13, 2006*/
			this.xmlDataFilePath = mailInfo.getXmlDataFilePath();
			InternetAddress[] toaddress = null;
			InternetAddress[] ccaddress = null;
			InternetAddress[] bccaddress = null;
			//Added by Gaurav Singh on 29-05-14
			InternetAddress from = null;

			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | Start ]
			//CommonConstants.setIBASEHOME();
			if(CommonConstants.TOMCAT_HOME == null || CommonConstants.TOMCAT_HOME.trim().length() == 0)
			{
				CommonConstants.setIBASEHOME();
			}
			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | End ]

			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] START
			/*Properties props= new Properties();
			props.put("mail.smtp.host", CommonConstants.SMTPHOST);

			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :START
			if(CommonConstants.SMTPPORT != null && CommonConstants.SMTPPORT.trim().length() > 0)
			{
				props.put("mail.smtp.port", CommonConstants.SMTPPORT);
			}
			if(CommonConstants.PROTOCOL_TYPE != null && "SSL".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			}
			else if(CommonConstants.PROTOCOL_TYPE != null && "TLS".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
			{
				props.put("mail.smtp.starttls.enable", "true");
			}*/
			//Changed made by Gular/Rahul on 06/12/14 to implement smtp port and protocol :END
			
			Session session = null;
			if ( CommonConstants.smtpSessions != null && CommonConstants.smtpSessions.get( CommonConstants.USERNAME ) != null )
			{
				//Changed by Prasad R on 16/12/2020 [set global credentials value while set session from smtpSessions]
				BaseLogger.log( "3", null, null, "set session from existing smtpSessions" );
				username = CommonConstants.USERNAME;
				password = CommonConstants.PASSWORD;
				session = CommonConstants.smtpSessions.get( CommonConstants.USERNAME );
				BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
			}
			else
			{
				Properties props = createIbaseMailServerProperties();
				Authenticator auth = null;
				if( CommonConstants.USERNAME != null && CommonConstants.PASSWORD != null )
				{
					props.put("mail.smtp.auth","true");
					//Changed by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
					//auth = new SMTPAuthenticator(null, false);
					auth = new SMTPAuthenticator();
					username = CommonConstants.USERNAME;
					password = CommonConstants.PASSWORD;
					BaseLogger.log( "3", null, null, "username : ["+ username +"], password : ["+ password +"]" );
				}
				BaseLogger.log( "3", null, null, "props : ["+ props +"]" );
				session = Session.getInstance(props,auth);
				if ( CommonConstants.smtpSessions == null )
				{
					CommonConstants.smtpSessions = new HashMap<String, Session>();
				}
				CommonConstants.smtpSessions.put( CommonConstants.USERNAME, session );
			}
			//Changed by Prasad R on 15/12/2020 [to resolve issue of invalid SMTP credentials] END

			session.setDebug(debug);
			//create message
			MimeMessage msg = new MimeMessage(session);

			//Commented and changes made by Gaurav Singh on 29-05-14 [ Start ]
			//To set the sender id dynamically. If found will set otherwise will set from CommonConstant.MAILFROM
			//InternetAddress from = new InternetAddress(CommonConstants.MAILFROM);
			if(this.mailFrom != null && this.mailFrom.trim().length() > 0)
		    {
		       from = new InternetAddress(this.mailFrom);
		    }
		    else
		    {
		       from = new InternetAddress(CommonConstants.MAILFROM);
		    }
			//Commented and changes made by Gaurav Singh on 29-05-14 [ End ]

			msg.setFrom(from);

			if(this.toAddr != null && ! this.toAddr.trim().equals("") && ! this.toAddr.equalsIgnoreCase("null"))
			{
				st_to = new StringTokenizer(this.toAddr,",");
				toaddress = new InternetAddress[st_to.countTokens()];
				int ctr = 0;
				while(st_to.hasMoreTokens())
				{
					InternetAddress address=new InternetAddress(st_to.nextToken());
					toaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting to Recipients .........");
				msg.setRecipients(Message.RecipientType.TO,toaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: To Address :"+this.toAddr);
			}

			int ctr = 0;
			if (this.ccAddr != null && !this.ccAddr.trim().equals("") && !this.ccAddr.equalsIgnoreCase("null") )
			{
				st_cc = new StringTokenizer(this.ccAddr,",");
				ctr = 0;
				ccaddress = new InternetAddress[st_cc.countTokens()];
				while(st_cc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_cc.nextToken());
					ccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting cc Recipients .........");
				msg.setRecipients(Message.RecipientType.CC,ccaddress);
			}
			else //vikrant 27/03/2006
			{
				//BaseLogger.log("9",null,null,"Warning: ccAddress :"+this.ccAddr);
			}

			if (this.bccAddr != null && !this.bccAddr.trim().equals("") && !this.bccAddr.equalsIgnoreCase("null") )
			{
				st_bcc = new StringTokenizer(this.bccAddr,",");
				ctr = 0;
				bccaddress=new InternetAddress[st_bcc.countTokens()];
				while(st_bcc.hasMoreTokens())
				{
					InternetAddress address = new InternetAddress(st_bcc.nextToken());
					bccaddress[ctr] = address;
					ctr++;
				}
				BaseLogger.log("3",null,null,"[EMail]Setting bcc Recipients .........");
				msg.setRecipients(Message.RecipientType.BCC,bccaddress);
			}
			else //vikrant 27/03/2006
			{
				BaseLogger.log("3",null,null,"Warning: bccAddress :"+this.bccAddr);
			}

			//Message Properties Setting
			//vikrant 27/03/2006
			if(this.subject!=null && !this.subject.trim().equalsIgnoreCase("null"))
			{
				msg.setSubject(subject);
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: Subject Not Defined !!!");
			}
			msg.setSentDate(new Date());

			//Message Body Creation
			BodyPart messageBody = new MimeBodyPart();
			BodyPart msgBodyForPage = null;
			BodyPart msgBodyForLink = null;
			Multipart multipart = new MimeMultipart();

			//part one: text message
			//vikrant 27/03/2006
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]Start
			/*if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
			{
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail start.
				//messageBody.setText(this.message);
				BaseLogger.log("9",null,null,"this.messageType:"+this.messageType);
				if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
				{
					messageBody.setContent(this.message, this.messageType);
				}else
				{
					messageBody.setText(this.message);
				}
				//Changed by Samadhan[S16FKAT002] on 25/11/2016 for send html type body mail end.
			}
			else
			{
				BaseLogger.log("9",null,null,"Warning: Message Not Defined !!!");
				messageBody.setText("");
			}
			multipart.addBodyPart(messageBody);*/
			//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]End
			//Samadhan
			if(inlineImages != null)
			{
				for (String key : inlineImages.keySet())
				{
					MimeBodyPart messageBodyPart1 = new MimeBodyPart();
					DataSource fds = new FileDataSource(inlineImages.get(key));
					messageBodyPart1.setDataHandler(new DataHandler(fds));
					messageBodyPart1.setHeader("Content-ID", "<"+key+">");
					multipart.addBodyPart(messageBodyPart1);
					BaseLogger.log("3",null,null,"inline path:"+inlineImages.get(key));
				}
			}
			//part two: attachment
			//vikrant 27/03/2006
			if (this.emailType != null && this.emailType.trim().length() > 0 && !this.emailType.trim().equalsIgnoreCase("null"))
			{
				if(this.emailType.equals("page"))
				{
					//vikrant 27/03/2006
					if (this.xmlDataFilePath != null)
					{
						//Changed By Prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] Start
						/*createdFileObj = new File(this.xmlDataFilePath);
						msgBodyForPage = new MimeBodyPart();
						DataSource source = new FileDataSource(createdFileObj);
						msgBodyForPage.setDataHandler(new DataHandler(source));
						BaseLogger.log("9",null,null,createdFileObj);

						//Changed by Gulzar on 07/11/14 - START
						//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
						}
						else
						{
							msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
						}
						//Changed by Gulzar on 07/11/14 - END
						BaseLogger.log("9",null,null,"File name :"+msgBodyForPage.getFileName()+":");
						multipart.addBodyPart(msgBodyForPage);*/
						if(this.xmlDataFilePath.indexOf(";") != -1)
						{
							BaseLogger.log("3",null,null,"xmlDataFilePath"+this.xmlDataFilePath);
							String[] dataFilePathArry = this.xmlDataFilePath.split(";");
							BaseLogger.log("3",null,null,"dataFilePathArry length [ "+dataFilePathArry.length+" ]");
							for(int i = 0; i < dataFilePathArry.length; i++)
							{
								createdFileObj = new File(dataFilePathArry[i]);
								msgBodyForPage = new MimeBodyPart();
								DataSource source = new FileDataSource(createdFileObj);
								msgBodyForPage.setDataHandler(new DataHandler(source));
								BaseLogger.log("3",null,null,createdFileObj);

								//Changed by Gulzar on 07/11/14 - START
								//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
								}
								else
								{
									msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
								}
								//Changed by Gulzar on 07/11/14 - END
								BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
								multipart.addBodyPart(msgBodyForPage);
								//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
								attachmentList.add(createdFileObj);
							}
						}
						else
						{
							createdFileObj = new File(this.xmlDataFilePath);
							msgBodyForPage = new MimeBodyPart();
							DataSource source = new FileDataSource(createdFileObj);
							msgBodyForPage.setDataHandler(new DataHandler(source));
							BaseLogger.log("3",null,null,createdFileObj);

							//Changed by Gulzar on 07/11/14 - START
							//msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							if((createdFileObj.toString()).lastIndexOf(File.separator) != -1)
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf(File.separator)+1, createdFileObj.toString().length()));
							}
							else
							{
								msgBodyForPage.setFileName((createdFileObj.toString()).substring((createdFileObj.toString()).lastIndexOf("\\")+1, createdFileObj.toString().length()));
							}
							//Changed by Gulzar on 07/11/14 - END
							BaseLogger.log("3",null,null,"File name :"+msgBodyForPage.getFileName()+":");
							multipart.addBodyPart(msgBodyForPage);
							//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
							attachmentList.add(createdFileObj);
						}
						//Added By prashant Chavan on 03-Sep-15 [For multiple Attachment request Id B15ESUN001] End
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: xmlDataFilePath :"+xmlDataFilePath);
					}
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][Start]
					if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
					{
						BaseLogger.log("3",null,null,"line no:441...this.messageType:"+this.messageType);
						if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
						{
							messageBody.setContent(this.message, this.messageType);
						}else
						{
							messageBody.setText(this.message);
						}
					}
					else
					{
						BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
						messageBody.setText("");
					}
					multipart.addBodyPart(messageBody);
					//Modified by Anjali R. on[25/10/2017][Purpose : Bug fixing in User Registration mail][End]
				}
				if(this.emailType.equals("link"))
				{
					//createdFileObj = mailInfo.getLinkFileObj(this.objName, this.refSer,  this.refID, this.lineNo); //builds the link to be send  //Danish Tuesday, June 13, 2006
					//Commented By Suraj on 12-Sept-2017 [For bug fixing in system generated emails]
					createdFileObj = mailInfo.getLinkFileObj( this.message ); //builds the link to be send
					msgBodyForLink = new MimeBodyPart();
					DataSource source = new FileDataSource(createdFileObj);
					msgBodyForLink.setDataHandler(new DataHandler(source));
					BaseLogger.log("3",null,null,"FileObjCreated ..."+ createdFileObj);
					multipart.addBodyPart(msgBodyForLink);
					//Added By Prasahnt Chavan  on 4-Sep-15 [For Multiple Attachment ]
					attachmentList.add(createdFileObj);
				}
			}
			else
			{
				BaseLogger.log("3",null,null,"Warning: emailType not found !!!");
				//Changed by Anjali R.[10/09/2017][Start][For bug fixing in system generated emails]
				if(this.message != null &&  !this.message.trim().equalsIgnoreCase("null"))
				{
					BaseLogger.log("3",null,null,"this.messageType:"+this.messageType);
					if (this.messageType != null && this.messageType.trim().length() > 0 && !this.messageType.trim().equalsIgnoreCase("null"))
					{
						messageBody.setContent(this.message, this.messageType);
					}
					else
					{
						if(this.message.toLowerCase().indexOf("<html>") != -1)
						{
							messageBody.setContent(this.message, "text/html; charset=utf-8");
						}
						else
						{
							messageBody.setText(this.message);
						}
					}
				}
				else
				{
					BaseLogger.log("3",null,null,"Warning: Message Not Defined !!!");
					messageBody.setText("");
				}
				multipart.addBodyPart(messageBody);
				//Changed by Anjali R.[10/09/2017][End][For bug fixing in system generated emails]
			}
			msg.setContent(multipart);// Put parts in message
			BaseLogger.log("3",null,null,"[EMail]Sending Mail..............................");
			if(msg.getRecipients(Message.RecipientType.TO) != null || msg.getRecipients(Message.RecipientType.CC) != null || msg.getRecipients(Message.RecipientType.BCC) != null)
			{
				Transport.send(msg);
			}

			BaseLogger.log("3",null,null,"[EMail]Message Sent ...");
			//Changed by Prashant Chavan on 04-Sep-15 for deleting the Multiple Attachments Start
			/*if(createdFileObj!= null)
			{
				createdFileObj.delete(); //deleting the temp file
			}*/
			if( attachmentList.size() > 0)
			{
				for(int i = 0;i < attachmentList.size(); i++)
				{
					File attachmentFileObj = attachmentList.get(i);
					attachmentFileObj.delete();
				}
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception :EMail :sendMail :==>\n"+e.getMessage());
			e.printStackTrace();
			throw e;
		}
		return "S";
	}
	//Added by Pankaj T on 12-01-18 [changes for multitenancy add overloaded method] - End
	
	//Added By Pankaj T. on 06-02-2020 to read email and download attachment customer wise on server - start
	public static String readEmailcontents(UserInfoBean userInfo) throws ITMException 
	{
		String responseStr = "";
		try
		{
			BaseLogger.log("3",null,null,"EMail.readEmailcontents() SMTPHOST:["+CommonConstants.SMTPHOST+"]");
			BaseLogger.log("3",null,null,"EMail.readEmailcontents() SMTPPORT:["+CommonConstants.SMTPPORT+"]");
			BaseLogger.log("3",null,null,"EMail.readEmailcontents() EMAIL_ID:["+CommonConstants.EMAIL_ID+"]");
			BaseLogger.log("3",null,null,"EMail.readEmailcontents() EMAIL_PASSWORD:["+CommonConstants.EMAIL_PASSWORD+"]");
			
			// create properties field
			Properties properties = new Properties();
			properties.put("mail.pop3.host", CommonConstants.SMTPHOST);
			properties.put("mail.pop3.port", CommonConstants.SMTPPORT);
			properties.put("mail.pop3.starttls.enable", "true");
			
			BaseLogger.log( "3", null, null, "props : ["+ properties +"]" );
			
			// create the POP3 store object and connect with the pop server
			Session emailSession = Session.getDefaultInstance(properties);
			Store store = emailSession.getStore("pop3s");
			store.connect(CommonConstants.SMTPHOST, CommonConstants.EMAIL_ID, CommonConstants.EMAIL_PASSWORD);
			
			// create the folder object and open it
			Folder emailFolder = store.getFolder("Inbox");
			emailFolder.open(Folder.READ_ONLY);
			
			// retrieve the messages from the folder in an array and print it
			//Message[] messages = emailFolder.getMessages();
			
			// Fetch unseen messages from inbox folder
	        Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));

	        // Sort messages from recent to oldest
	        Arrays.sort( messages, ( m1, m2 ) -> {
	        	try 
	        	{
	        		return m2.getSentDate().compareTo( m1.getSentDate() );
	        	} 
	        	catch ( MessagingException e ) 
	        	{
	        		throw new RuntimeException( e );
	        	}
	        });
	        
			BaseLogger.log("3",null,null,"EMail.readEmailcontents() messages.length :[" + messages.length + "]");
			boolean isAttachment = false;
			for (int i = 0, n = messages.length; i < n; i++) 
			{
				Message message = messages[i];
				BaseLogger.log("3",null,null,"---------------------------------");
				BaseLogger.log("3",null,null,"Email Number :[" + (i + 1) + "]");
				BaseLogger.log("3",null,null,"Subject :[" + message.getSubject() + "]");
				BaseLogger.log("3",null,null,"From :[" + message.getFrom()[0] + "]");
				BaseLogger.log("3",null,null,"To :[" + message.getAllRecipients().toString() + "]");
				BaseLogger.log("3",null,null,"Received Date :[" + message.getReceivedDate() + "]");
				String customerName = ""+message.getFrom()[0];
				customerName = customerName.substring(customerName.indexOf("@")+1);
				customerName = customerName.substring(0, customerName.indexOf("."));
				BaseLogger.log("3",null,null,"Customer Name:["+customerName+"]");
				BaseLogger.log("3",null,null,"---------------------------------");
				String contentType = message.getContentType();
				BaseLogger.log("3",null,null,"EMail.readEmailcontents() contentType:["+contentType+"]");
                String messageContent = "";
 
                // store attachment file name, separated by comma
                String attachFiles = "";
				if (contentType.contains("multipart")) 
				{
					// content may contain attachments
					Multipart multiPart = (Multipart) message.getContent();
					int numberOfParts = multiPart.getCount();
					BaseLogger.log("3",null,null,"EMail.readEmailcontents() numberOfParts:["+numberOfParts+"]");
					for (int partCount = 0; partCount < numberOfParts; partCount++) 
					{
						MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
						if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) 
						{
							// this part is attachment
							String fileName = part.getFileName();
							BaseLogger.log("3",null,null,"EMail.readEmailcontents() fileName:["+fileName+"]");
							attachFiles += fileName + ", ";
							String folderPath = CommonConstants.JBOSSHOME + File.separator + "server" + File.separator +"default"+ File.separator + "deploy" + File.separator + "ibase.ear" + File.separator + "ibase.war" + File.separator + "email_attachments" + File.separator + customerName;
							File file = new File(folderPath);
							if( !file.exists() )
							{
								file.mkdirs();
							}
							part.saveFile(folderPath + File.separator + fileName);
							SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");  
						    Date date = new Date();
						    String currentDate = formatter.format(date);
						    BaseLogger.log("3",null,null,"EMail.readEmailcontents() CurrentDate:["+currentDate+"]");
						    String newFileName = currentDate+"_"+fileName;
						    BaseLogger.log("3",null,null,"EMail.readEmailcontents() newFileName :["+newFileName+"]");
						    
						    File oldFile = new File(folderPath + File.separator + fileName); 
						    oldFile.renameTo(new File(folderPath + File.separator + newFileName));
						    isAttachment = true;
						} 
						else 
						{
							// this part may be the message content
							messageContent = part.getContent().toString();
							BaseLogger.log("3",null,null,"EMail.readEmailcontents() messageContent:["+messageContent+"]");
						}
					}

					if (attachFiles.length() > 1) 
					{
						attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
						BaseLogger.log("3",null,null,"EMail.readEmailcontents() Attachments:["+attachFiles+"]");
					}
				} 
				else if (contentType.contains("text/plain") || contentType.contains("text/html")) 
				{
					Object content = message.getContent();
					if (content != null) 
					{
						messageContent = content.toString();
					}
				}
			}

			if( messages.length == 0 )
			{
				responseStr = "There is no unread emails.";
			}
			else if( isAttachment ) 
			{
				responseStr = "Email attcahments downloaded successfully on location " + CommonConstants.JBOSSHOME + File.separator + "email_attachments with customer wise.";
			}
			else
			{
				responseStr = "There is no such attcahments in email.";
			}
				
			// close the store and folder objects
			emailFolder.close(false);
			store.close();
		}
		catch (NoSuchProviderException e)
		{
			BaseLogger.log("0",null,null,"EMail.readEmailcontents() NoSuchProviderException["+E12GenericUtility.getStackTrace(e)+"]");
			throw new ITMException(e);
		}
		catch (MessagingException e)
		{
			BaseLogger.log("0",null,null,"EMail.readEmailcontents() MessagingException["+E12GenericUtility.getStackTrace(e)+"]");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"EMail.readEmailcontents() Exception["+E12GenericUtility.getStackTrace(e)+"]");
			throw new ITMException(e);
		}
		return responseStr;
	}
	//Added By Pankaj T. on 06-02-2020 to read email and download attachment customer wise on server - end
	
	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
	private Properties createSMTPServerProperties( UserInfoBean userInfo )
	{
		Properties props = new Properties();
		props.put("mail.smtp.host", userInfo.getSmtpHost());
		
		if( userInfo.getSmtpPort() != null && userInfo.getSmtpPort().trim().length() > 0)
		{
			props.put("mail.smtp.port", userInfo.getSmtpPort());
		}
		if(userInfo.getSmtpProtocolType() != null && "SSL".equalsIgnoreCase(userInfo.getSmtpProtocolType()))
		{
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		else if(userInfo.getSmtpProtocolType() != null && "TLS".equalsIgnoreCase(userInfo.getSmtpProtocolType()))
		{
			props.put("mail.smtp.starttls.enable", "true");
		}
		return props;
	}
	
	private Properties createIbaseMailServerProperties()
	{
		Properties props = new Properties();
		props.put("mail.smtp.host", CommonConstants.SMTPHOST);
		
		if(CommonConstants.SMTPPORT != null && CommonConstants.SMTPPORT.trim().length() > 0)
		{
			props.put("mail.smtp.port", CommonConstants.SMTPPORT);
		}
		if(CommonConstants.PROTOCOL_TYPE != null && "SSL".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
		{
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		else if(CommonConstants.PROTOCOL_TYPE != null && "TLS".equalsIgnoreCase(CommonConstants.PROTOCOL_TYPE))
		{
			props.put("mail.smtp.starttls.enable", "true");
			//Added by Gagan on 03-Oct-2023 [ As suggested by Danish Sir to avoid TLS older version usage  ]
			// Not to do right now as discussed with Danish sir.
//			props.put("mail.smtp.ssl.protocols", "TLSv1.2"); 

		}
		return props;
	}
	//Added by Pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end

	/*
	 * Added by Gagan B. on 07-OCT-24 for handling images in the HTML
	 * replacing base64 content with cid to resolve image rendering issues in Gmail-- START
	 * */
	private static List<String> extractBase64ImageDataList(String htmlContent) {
        List<String> base64Images = new ArrayList<>();
        String base64ImagePattern = "data:image/[^;]+;base64,([^\\\"]+)";
        Pattern pattern = Pattern.compile(base64ImagePattern);
        Matcher matcher = pattern.matcher(htmlContent);

        while (matcher.find()) {
            base64Images.add(matcher.group(1)); // Extract each Base64 image data
        }

        return base64Images;
    }
	
	 private static String replaceBase64WithCid(String htmlContent, List<String> cids) {
	        String base64ImagePattern = "data:image/[^;]+;base64,[^\\\"]+";
	        Pattern pattern = Pattern.compile(base64ImagePattern);
	        Matcher matcher = pattern.matcher(htmlContent);

	        StringBuffer updatedHtmlContent = new StringBuffer();
	        int i = 0;
	        while (matcher.find() && i < cids.size()) {
	            matcher.appendReplacement(updatedHtmlContent, "cid:" + cids.get(i));
	            i++;
	        }
	        matcher.appendTail(updatedHtmlContent);

	        return updatedHtmlContent.toString();
	    }
		/*
		 * Added by Gagan B. on 07-OCT-24 for handling images in the HTML 
		 * replacing base64 content with cid to resolve image rendering issues in Gmail-- START
		 */
	 
	private void updateTransactionMailStatus(String objName, String refID, UserInfoBean userInfo) 
	{
		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		PreparedStatement preparedStatement = null;
		ResultSet rs = null;
		try
		{
			BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() objName : [" + objName + "]");
			BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() refID   : [" + refID + "]");
			ConnDriver connDriver = new ConnDriver();
			connection = connDriver.getConnectDB( userInfo.getTransDB() );
			String sql = "SELECT TRAN_ID_COL, TABLE_NAME FROM TRANSETUP WHERE TRAN_WINDOW = ?";
			pstmt = connection.prepareStatement(sql);
			pstmt.setString(1, "w_"+objName.toLowerCase());
			resultSet = pstmt.executeQuery();
			if( resultSet.next() )
			{
				String tableName = resultSet.getString("TABLE_NAME");
				String tranIdCol = resultSet.getString("TRAN_ID_COL");
				BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() Transaction tableName : [" + tableName + "]");
				BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() Transaction tranId    : [" + tranIdCol + "]");
				if( tableName != null && tranIdCol != null )
				{
					String database = connDriver.getDBName();
					String sqlString = "";
					if("oracle".equalsIgnoreCase(database))
					{
						sqlString = "SELECT COUNT(*) AS COUNT FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?";
					}
					else if( "mysql".equalsIgnoreCase(database) || "mssql".equalsIgnoreCase(database) || "db2".equalsIgnoreCase(database) || "pgsql".equalsIgnoreCase(database) )
					{
						sqlString = "SELECT COUNT(*) AS COUNT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?";
					}
					preparedStatement = connection.prepareStatement(sqlString);
					preparedStatement.setString(1, tableName);
					preparedStatement.setString(2, "EMAIL_SENT_STAT");
					rs = preparedStatement.executeQuery();
					int count = 0;
					if( rs.next() )
					{
						count = rs.getInt("COUNT");
					}
					BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() column count : [" + count + "]");
					preparedStatement.close();
					preparedStatement = null;
					rs.close();
					rs = null;
					
					if( count > 0 )
					{
						String updateSql = "UPDATE " + tableName + " SET EMAIL_SENT_STAT = 'Y' WHERE " + tranIdCol + " = '" + refID + "'";
						preparedStatement = connection.prepareStatement(updateSql);
						int updateCount = preparedStatement.executeUpdate();
						BaseLogger.log("3", null, null, "EMail.updateTransactionMailStatus() email status updateCount : [" + updateCount + "]");
						connection.commit();
						preparedStatement.close();
						preparedStatement = null;
					}
				}
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if( resultSet != null )
			{
				resultSet.close();
				resultSet = null;
			}
			if( connection != null )
			{
				connection.close();
				connection = null;
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0", null, null, "EMail.updateTransactionMailStatus() Exception : [" + E12GenericUtility.getStackTrace(e) + "]");
		}
		finally
		{
			try
			{
				if(preparedStatement != null )
				{
					preparedStatement.close();
					preparedStatement = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( resultSet != null )
				{
					resultSet.close();
					resultSet = null;
				}
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( connection != null )
				{
					connection.close();
					connection = null;
				}
			}
			catch (Exception e2)
			{
				BaseLogger.log("0", null, null, "EMail.updateTransactionMailStatus() finally Exception : [" + E12GenericUtility.getStackTrace(e2) + "]");
			}
		}
	}
	
	//Method Added by Amol S on 29-May-25  -strt
	public String sendEmailAndSms(String formatCode,String mailXMLStr, UserInfoBean userInfo) {
		

	    BaseLogger.log("3", null, null, "sendEmailAndSms Method Called ==>");
	    BaseLogger.log("3", null, null, "userInfo:: ==>"+userInfo);
	    BaseLogger.log("3", null, null, "mailXMLStr:: ==>"+mailXMLStr);

	    Connection conn = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;

	    ConnDriver connDriver = new ConnDriver();

	    String sql = "SELECT SEND_TO, COPY_TO, BLIND_COPY, SUBJECT, BODY_TEXT FROM MAIL_FORMAT WHERE FORMAT_CODE = ?";

	    String mailTo = "", mailCc = "", mailBcc = "", mailSubject = "", mailBody = "", emailSend = "", smsSend = "";

	    try {
	        conn = connDriver.getConnectDB(userInfo.getTransDB());
	        pstmt = conn.prepareStatement(sql);
	        pstmt.setString(1, formatCode);
	        rs = pstmt.executeQuery();

	        if (rs.next()) {
	            mailTo = checkNull(rs.getString("SEND_TO"));
	            mailCc = checkNull(rs.getString("COPY_TO"));
	            mailBcc = checkNull(rs.getString("BLIND_COPY"));
	            mailSubject = checkNull(rs.getString("SUBJECT"));
	            mailBody = checkNull(rs.getString("BODY_TEXT"));
	        }

	        BaseLogger.log("3", null, null, "Mail To: " + mailTo);
	        BaseLogger.log("3", null, null, "Mail CC: " + mailCc);
	        BaseLogger.log("3", null, null, "Mail Subject: " + mailSubject);

	        // Split the SEND_TO string
	        String[] recipients = mailTo.split(",");
	        String emailRecipient = "";
	        String smsRecipient = "";

	        for (String recipient : recipients) {
	            recipient = recipient.trim();
	            
	            if (recipient.matches("\\d{10}")) {
	                BaseLogger.log("3", null, null, "Inside the If block For Mobile No");
	                smsRecipient = recipient;
	    	        BaseLogger.log("3", null, null, "SmSRecipient: " + smsRecipient);

	            }
	            else  if (recipient.contains("@")) {
	                BaseLogger.log("3", null, null, "Inside the If block For Email");
	                emailRecipient = recipient;
	            }
	        }
	        

	         if (!smsRecipient.isEmpty())
	        {
		       System.out.println("smsRecipient Mob No==>" + smsRecipient);
			  String userId = userInfo.getLoginCode();
			  String xtraParams = "loginCode=" + userId + "~~loginEmpCode" + userId;
  	          BaseLogger.log("3", null, null, "userId--> " + userId);
    	      E12SMSComp E12SMSComp=new E12SMSComp();
    	      E12SMSComp.sendSms(smsRecipient, formatCode,userInfo);
    	      //to send the sms call the method here 
   	      
    	      //E12SMSComp.sendSMS(mailXMLStr,formatCode,xtraParams,userInfo);
	        }
	        // Prepare and send email
	          if (!emailRecipient.isEmpty()) {
			       System.out.println(" Inside the Email blovk ==>" );

	            String mailToClient =
	                "<ROOT><MAIL><EMAIL_TYPE>page</EMAIL_TYPE><ENTITY_CODE>BASE</ENTITY_CODE>" +
	                "<ENTITY_TYPE>E</ENTITY_TYPE><SUBJECT>" + mailSubject + "</SUBJECT>" +
	                "<BODY_TEXT>" + mailBody + "</BODY_TEXT><TO_ADD>" + emailRecipient.trim() + "</TO_ADD><CC_ADD>" + mailCc + "</CC_ADD>" +
	                "<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT></MAIL></ROOT>";

	            System.out.println("mailToClient::==>" + mailToClient);
	            emailSend = sendMail( mailToClient, "ITM", userInfo);
    	        BaseLogger.log("3", null, null, "EmailSend: " + emailSend);

	        }
	        
	       

	    } catch (Exception e) {

	        e.printStackTrace();
	    } finally {
	        try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); }
	        try { if (pstmt != null) pstmt.close(); } catch (Exception e) { e.printStackTrace(); }
	        try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); }
	    }

	    return "Email: " + emailSend + ", SMS: " + smsSend;
	}
	
	//Added new method sendEmailAndSmsNdWhtsApp() to send msg,email, whtsapp sms simeltniously -- Start
	
    public String sendEmailAndSmsNdWhtsApp(String formatCode,String mailXMLStr, UserInfoBean userInfo) {
		

	    BaseLogger.log("3", null, null, "sendEmailAndSms Method Called on19-Jun-25 ==>");
	    BaseLogger.log("3", null, null, "userInfo:: ==>"+userInfo);
	    BaseLogger.log("3", null, null, "mailXMLStr:: ==>"+mailXMLStr);

	    Connection conn = null;
	    PreparedStatement pstmt = null;
	    ResultSet rs = null;

	    ConnDriver connDriver = new ConnDriver();

	    String sql = "SELECT SEND_TO, COPY_TO, BLIND_COPY, SUBJECT, BODY_TEXT,TEMPLATE_NAME FROM MAIL_FORMAT WHERE FORMAT_CODE = ?";

	    String mailTo = "", mailCc = "", mailBcc = "", mailSubject = "", mailBody = "", emailSend = "", smsSend = "",mailTemplate="";

	    try {
	        conn = connDriver.getConnectDB(userInfo.getTransDB());
	        pstmt = conn.prepareStatement(sql);
	        pstmt.setString(1, formatCode);
	        rs = pstmt.executeQuery();

	        if (rs.next()) {
	            mailTo = checkNull(rs.getString("SEND_TO"));
	            mailCc = checkNull(rs.getString("COPY_TO"));
	            mailBcc = checkNull(rs.getString("BLIND_COPY"));
	            mailSubject = checkNull(rs.getString("SUBJECT"));
	            mailBody = checkNull(rs.getString("BODY_TEXT"));
	            mailTemplate = checkNull(rs.getString("TEMPLATE_NAME"));

	        }

	        BaseLogger.log("3", null, null, "Mail To: " + mailTo);
	        BaseLogger.log("3", null, null, "Mail CC: " + mailCc);
	        BaseLogger.log("3", null, null, "Mail Subject: " + mailSubject);

	        // Split the SEND_TO string
	        String[] recipients = mailTo.split(",");
	        String emailRecipient = "";
	        String smsRecipient = "";

	        for (String recipient : recipients) {
	            recipient = recipient.trim();
	            
	            if (recipient.matches("\\d{10}")) {
	                BaseLogger.log("3", null, null, "Inside the If block For Mobile No");
	                smsRecipient = recipient;
	    	        BaseLogger.log("3", null, null, "SmSRecipient: " + smsRecipient);

	            }
	            else  if (recipient.contains("@")) {
	                BaseLogger.log("3", null, null, "Inside the If block For Email==>");
	                emailRecipient = recipient;
	            }
	        }
	        

	         if (!smsRecipient.isEmpty())
	        {
		       System.out.println("smsRecipient Mob No==>" + smsRecipient);
			  String userId = userInfo.getLoginCode();
			  String xtraParams = "loginCode=" + userId + "~~loginEmpCode" + userId;
  	          BaseLogger.log("3", null, null, "userId--> " + userId);
    	      E12SMSComp E12SMSComp=new E12SMSComp();
    	      E12SMSComp.sendSms(smsRecipient, formatCode,userInfo);
    	      //to send the whtsapp sms call the method here 
    	      
    	      E12GenericUtility e12GenericUtility = new E12GenericUtility();
    	      String whatsappConfig = getDBAccess().getDBColumnValue("ENTERPRISE", "WHATSAPP_SETTING", "ENTERPRISE = '" + userInfo.getEnterprise() + "'", userInfo.getTransDB());
		      BaseLogger.log("3", null, null, "WhatsApp Config::: [" + whatsappConfig + "]");
		      WhatsAppComm WhatsAppComm =new WhatsAppComm();
  	          BaseLogger.log("3", null, null, "formatCode==--> " + formatCode);
  	          BaseLogger.log("3", null, null, "Mobile No==--> " + smsRecipient);

  	          
  	          BaseLogger.log("3", null, null, "WhatsAppComm.sendWhatsApp::  mailXMLStr" + mailXMLStr.toString());
			  WhatsAppComm.sendWhatsApp(formatCode,whatsappConfig,smsRecipient, userInfo,mailXMLStr, "");
			  e12GenericUtility.writeCommunicationLog(userInfo, false, "W", "S", "WhatsApp sent successfully", smsRecipient, this.ccAddr, this.bccAddr, this.subject, formatCode, 0, null);
			  // return "S";
    	      
    	      //E12SMSComp.sendSMS(mailXMLStr,formatCode,xtraParams,userInfo);
	        }
	        // Prepare and send email
	          if (!emailRecipient.isEmpty()) {
			       System.out.println(" Inside the Email blovk ==>" );

	            String mailToClient =
	                "<ROOT><MAIL><EMAIL_TYPE>page</EMAIL_TYPE><ENTITY_CODE>BASE</ENTITY_CODE>" +
	                "<ENTITY_TYPE>E</ENTITY_TYPE><SUBJECT>" + mailSubject + "</SUBJECT>" +
	                "<BODY_TEXT>" + mailBody + "</BODY_TEXT><TO_ADD>" + emailRecipient.trim() + "</TO_ADD><CC_ADD>" + mailCc + "</CC_ADD>" +
	                "<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT></MAIL></ROOT>";

	            System.out.println("mailToClient::==>" + mailToClient);
	            emailSend = sendMail( mailToClient, "ITM", userInfo);
    	        BaseLogger.log("3", null, null, "EmailSend: " + emailSend);

	        }
	        
	       

	    } catch (Exception e) {

	        e.printStackTrace();
	    } finally {
	        try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); }
	        try { if (pstmt != null) pstmt.close(); } catch (Exception e) { e.printStackTrace(); }
	        try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); }
	    }

	    return "Email: " + emailSend + ", SMS: " + smsSend;
	}
	//Added new method sendEmailAndSmsNdWhtsApp() to send msg,email, whtsapp sms simeltniously -- End


	
	
	private String checkNull(String input)
	{
		if (input == null)
		{
			input = "";
		}
		return input;
	}

	
}