using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Data.OracleClient;
using System.Data.Odbc;
using System.Text.RegularExpressions;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace HRMSEmailService
{
/*
* - SMTP Configurations
* - In mail CC Option
* - In mail FORWAR TO Option
* - IN MAIL ATTACHMENT Option
* - Mail format validation
*/
///
public partial class HRMSEmailService : ServiceBase
{
private System.Timers.Timer timer = null;
static string _errorLogTag = System.Configuration.ConfigurationSettings.AppSettings["EventLogTag"];
public HRMSEmailService()
{
InitializeComponent();
string servicepollinterval = System.Configuration.ConfigurationManager.AppSettings
["servicepollinterval"].ToString();
double interval = 10000;
try
{
interval = Convert.ToDouble(servicepollinterval);
}
catch (Exception) { }
timer = new System.Timers.Timer(interval);
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.ServiceTimer_Tick);
timer.Start();
}
protected override void OnStart(string[] args)
{
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}
protected override void OnStop()
{
timer.AutoReset = false;
timer.Enabled = false;
}
protected override void OnPause()
{
this.timer.Stop();
}
protected override void OnContinue()
{
this.timer.Start();
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
this.timer.Stop();
//CheckHRMSDBConnection();
//SendEmail();
SendAsyncEmail();
this.timer.Start();
}
public void SendEmail()
{
//string con = GetHRMSConnection();
DataSet _dsMailQueue = GetTOPNRecords();
#region Log DataSet Count
if (_errorLogTag == "1")
{
string _dsmsgs=string.Empty;
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "SendEmail"; //Method prototype
if (_dsMailQueue!=null)
_dsmsgs= "Select Top 10 rows --> received " + _dsMailQueue.Tables[0].Rows.Count + "";
else
_dsmsgs = "Select Top 10 rows --> Dataset is null in case of getting 10 records from table cause error.";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
string mailMessage;
if (_dsMailQueue != null)
{
string smtpserver="";
smtpserver = System.Configuration.ConfigurationManager.AppSettings["smtpserver"];
SmtpClient smtp = new SmtpClient(smtpserver);
foreach (DataRow _drMailQueue in _dsMailQueue.Tables[0].Rows)
{
//start:
try
{
mailMessage = _drMailQueue["MQ_Body"].ToString();
string MailFrom = System.Configuration.ConfigurationSettings.AppSettings["mailFrom"];
string MailReplyTo = System.Configuration.ConfigurationSettings.AppSettings["mailReplyTo"];
string MailFromPwd = System.Configuration.ConfigurationSettings.AppSettings["mailFromPwd"];
string DisplayName = System.Configuration.ConfigurationSettings.AppSettings["DisplayName"];
string MailTo = _drMailQueue["MQ_Recipient"].ToString();
string MailSubject = _drMailQueue["MQ_Subject"].ToString();
string MailMessage = mailMessage;
string Port = System.Configuration.ConfigurationManager.AppSettings["port"];
string EnableSSL = System.Configuration.ConfigurationManager.AppSettings["enablessl"];
//string DomainName = System.Configuration.ConfigurationManager.AppSettings["DomainName"];
//string UserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
string UserName = System.Configuration.ConfigurationManager.AppSettings["mailFrom"];
if (IsEmail(_drMailQueue["MQ_Recipient"].ToString())) //proceed in case of valid Email Address
{
MailMessage mail = new MailMessage();
mail.To.Add(MailTo);
//mail.ReplyTo = new MailAddress(MailReplyTo, DisplayName);
mail.From = new MailAddress(MailFrom, DisplayName);
mail.Subject = MailSubject;
mail.Body = mailMessage;
System.Net.NetworkCredential basicAuthenticationInfo;
// if (!string.IsNullOrEmpty(DomainName))
// basicAuthenticationInfo = new System.Net.NetworkCredential(UserName, MailFromPwd, DomainName);
// else
//{
UserName = MailFrom;
basicAuthenticationInfo = new System.Net.NetworkCredential(UserName, MailFromPwd);
// smtp.Credentials = basicAuthenticationInfo;
// }
#region Log DataSet Count
if (_errorLogTag == "1")
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "Make Smtp object"; //Method prototype
string _dsmsgs = "Check Smtp Method created " + smtp + "";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
if (EnableSSL.ToLower() == "Yes".ToLower())
{
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
}
else
{
smtp.EnableSsl = false;
smtp.UseDefaultCredentials = true;
}
smtp.Credentials = basicAuthenticationInfo;
mail.IsBodyHtml = true;
smtp.Port = int.Parse(Port);
smtp.Send(mail);
smtp.Dispose();
// Update Mail status
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Sent' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
// End
}
else
{
// Update Mail status
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Wrong Email Address' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
// End
}
}
catch (Exception ex)
{
//int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Error' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='" + ex.Message.ToString() + " - " + ex.InnerException.ToString().Replace("'", "''") + "' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
//goto start;
}
finally
{
smtp.Dispose();
}
}
}
}
public void SendEmailForExchangeServer()
{
//string con = GetHRMSConnection();
DataSet _dsMailQueue = GetTOPNRecords();
#region Log DataSet Count
if (_errorLogTag == "1")
{
string _dsmsgs = string.Empty;
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "SendEmail"; //Method prototype
if (_dsMailQueue != null)
_dsmsgs = "Select Top 10 rows --> received " + _dsMailQueue.Tables[0].Rows.Count + "";
else
_dsmsgs = "Select Top 10 rows --> Dataset is null in case of getting 10 records from table cause error.";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
string mailMessage;
if (_dsMailQueue != null)
{
foreach (DataRow _drMailQueue in _dsMailQueue.Tables[0].Rows)
{
//start:
try
{
mailMessage = _drMailQueue["MQ_Body"].ToString();
string MailFrom = System.Configuration.ConfigurationSettings.AppSettings["mailFrom"];
string MailReplyTo = System.Configuration.ConfigurationSettings.AppSettings["mailReplyTo"];
string MailFromPwd = System.Configuration.ConfigurationSettings.AppSettings["mailFromPwd"];
string DisplayName = System.Configuration.ConfigurationSettings.AppSettings["DisplayName"];
string MailTo = _drMailQueue["MQ_Recipient"].ToString();
string MailSubject = _drMailQueue["MQ_Subject"].ToString();
string MailMessage = mailMessage;
//string smtpserver = System.Configuration.ConfigurationManager.AppSettings["smtpserver"];
//string Port = System.Configuration.ConfigurationManager.AppSettings["port"];
//string EnableSSL = System.Configuration.ConfigurationManager.AppSettings["enablessl"];
if (IsEmail(_drMailQueue["MQ_Recipient"].ToString())) //proceed in case of valid Email Address
{
ExchangeService service = new ExchangeService();
service.AutodiscoverUrl(MailFrom);
EmailMessage message = new EmailMessage(service);
message.Subject = MailSubject;
message.Body = mailMessage;
message.ToRecipients.Add(MailTo);
message.Save();
message.SendAndSaveCopy();
// Update Mail status
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Sent' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
// End
}
else
{
// Update Mail status
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Wrong Email Address' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
// End
}
}
catch (Exception ex)
{
//int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Error' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='" + ex.Message.ToString() + " - " + ex.InnerException.ToString().Replace("'", "''") + "' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
//goto start;
}
}
}
}
private static string GetHRMSConnection()
{
if (System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"].ToString() == "SYBASE")
{
return System.Configuration.ConfigurationSettings.AppSettings["HRMSConnectionStringSyBase"].ToString();
}
else if (System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"].ToString() == "ORACLE")
{
return System.Configuration.ConfigurationSettings.AppSettings["HRMSConnectionStringORACLE"].ToString();
}
else
{
return System.Configuration.ConfigurationSettings.AppSettings["HRMSConnectionStringSqlServer"].ToString();
}
}
public DataSet GetHRMSDataSet(string sql)
{
string HRMSDatabaseName = System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"];
DataSet ds = new DataSet();
if (HRMSDatabaseName.ToUpper() == "SQLSERVER")
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection con = new SqlConnection(GetHRMSConnection());
SqlCommand cmd = new SqlCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
else if (HRMSDatabaseName.ToUpper() == "MYSQL")
{
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetHRMSConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
else if (HRMSDatabaseName.ToUpper() == "ORACLE")
{
OracleDataAdapter da = new OracleDataAdapter();
OracleConnection con = new OracleConnection(GetHRMSConnection());
OracleCommand cmd = new OracleCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
return null;
}
public DataSet GetTOPNRecords()
{
#region Log DataSet Count
if (_errorLogTag == "1")
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "Check Database Connection"; //Method prototype
string _dsmsgs = "Get topNRecords" ;
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
string sql = string.Empty;
string HRMSDatabaseName = System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"];
DataSet ds = new DataSet();
#region Log DataSet Count
if (_errorLogTag == "1")
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "Check Database Connection"; //Method prototype
string _dsmsgs = "Get database name" + HRMSDatabaseName + "";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
if (HRMSDatabaseName.ToUpper() == "SQLSERVER")
{
sql = "SELECT TOP 10 * FROM ADMIN_MAILQUEUE WHERE MQ_STATUS = 'Pending'";
#region Log DataSet Count
if (_errorLogTag == "1")
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "Check Database Connection"; //Method prototype
string _dsmsgs = "Query " + sql + "";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection con = new SqlConnection(GetHRMSConnection());
SqlCommand cmd = new SqlCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
#region Log DataSet Count
if (_errorLogTag == "1")
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = "Check Database Connection"; //Method prototype
string _dsmsgs = "DB Conection " + ex.Message+ "";
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
ds = null;
}
}
else if (HRMSDatabaseName.ToUpper() == "MYSQL")
{
sql = "SELECT * FROM ADMIN_MAILQUEUE WHERE MQ_STATUS = 'Pending' LIMIT 10";
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetHRMSConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
else if (HRMSDatabaseName.ToUpper() == "ORACLE")
{
sql = "select * from ADMIN_MAILQUEUE where MQ_STATUS = 'Pending' AND ROWNUM <= 10";
OracleDataAdapter da = new OracleDataAdapter();
OracleConnection con = new OracleConnection(GetHRMSConnection());
OracleCommand cmd = new OracleCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
else if (HRMSDatabaseName.ToUpper() == "SYBASE")
{
sql = "SET rowcount 10 SELECT * FROM ADMIN_MAILQUEUE WHERE MQ_STATUS = 'Pending'";
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetHRMSConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ds = null;
}
}
return null;
}
public int ExecuteQuery(string query)
{
int execSuccess = 0;
try
{
execSuccess = InsertUpdateDeleteInHRMSDataTable(query);
return execSuccess;
}
catch (Exception ex)
{
return 0;
}
}
public int InsertUpdateDeleteInHRMSDataTable(string sql)
{
string DataBase = System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"];
int rt = 0;
if (DataBase.ToUpper() == "SQLSERVER")
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection con = new SqlConnection(GetHRMSConnection());
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Connection.Open();
rt = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return rt;
}
else if (DataBase.ToUpper() == "MYSQL")
{
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetHRMSConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
cmd.Connection.Open();
rt = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return rt;
}
else if (DataBase.ToUpper() == "ORACLE")
{
OracleDataAdapter da = new OracleDataAdapter();
OracleConnection con = new OracleConnection(GetHRMSConnection());
OracleCommand cmd = new OracleCommand(sql, con);
cmd.Connection.Open();
rt = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return rt;
}
return rt;
}
public bool IsEmail(string Email)
{
//string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
//@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
//@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
string strRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
Regex re = new Regex(strRegex);
if (re.IsMatch(Email))
return (true);
else
return (false);
}
void CreatHRMSErrorLogFile(string ex)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + ex);
sw.Flush();
sw.Close();
}
catch
{
}
}
void CheckHRMSDBConnection()
{
try
{
string DataBase = System.Configuration.ConfigurationSettings.AppSettings["HRMSDatabaseName"];
if (DataBase.ToUpper() == "SQLSERVER")
{
SqlConnection con = new SqlConnection(GetHRMSConnection());
con.Open();
//CreatHRMSErrorLogFile("Connection stablished successfully.");
}
else if (DataBase.ToUpper() == "MYSQL")
{
OdbcConnection con = new OdbcConnection(GetHRMSConnection());
con.Open();
CreatHRMSErrorLogFile("Connection stablished successfully.");
}
else if (DataBase.ToUpper() == "ORACLE")
{
OracleConnection con = new OracleConnection(GetHRMSConnection());
con.Open();
CreatHRMSErrorLogFile("Connection stablished successfully.");
}
}
catch (Exception ex)
{
//CreatHRMSErrorLogFile(ex.Message);
}
}
#region Changes Made by Raza Hussain Rajpar
//CC, Forwar and Attachement
MailMessage AttacheFileToEMail(string fromMail, string toMail,string subject,string body, string pathOfAttachFile)
{
MailMessage message = new MailMessage(fromMail, toMail, subject, body);
System.Net.Mail.Attachment _attachment = new System.Net.Mail.Attachment(pathOfAttachFile /*Path of attached file*/);
message.Attachments.Add(_attachment);
message.IsBodyHtml = true;
return message;
}
///
/// AttacheFileToEMail
/// Created by: Raza Hussain Rajpar
/// Created On : 22/August/2013
///
/// source email
/// destination / direct email
/// title of email
/// context of email
/// attached files path
/// multiple email must be separated by comma
/// multiple email must be separated by comma
///
MailMessage AttacheFileToEMail(string fromMail, string toMail, string subject, string body, string pathOfAttachFile, string ccTo, string bccTo)
{
MailMessage message = new MailMessage(fromMail, toMail, subject, body);
System.Net.Mail.Attachment _attachment = new System.Net.Mail.Attachment(pathOfAttachFile /*Path of attached file*/);
message.Attachments.Add(_attachment);
message.IsBodyHtml = true;
message.Bcc.Add(bccTo);
message.CC.Add(ccTo);
return message;
}
MailMessage AttacheFileToEMail(MailMessage message, string pathOfAttachFile)
{
System.Net.Mail.Attachment _attachment = new System.Net.Mail.Attachment(pathOfAttachFile /*Path of attached file*/);
message.Attachments.Add(_attachment);
return message;
}
System.Net.NetworkCredential ConfigureNetworkCredntials(string domainName, string userName, string password)
{
System.Net.NetworkCredential nwkCredential = new System.Net.NetworkCredential();
if (!String.IsNullOrEmpty(domainName))
nwkCredential.Domain = domainName;
nwkCredential.UserName = userName;
nwkCredential.Password = password;
return nwkCredential;
}
void ConfigureSMTP(String hostName, int portNumber, System.Net.NetworkCredential nwkCredential, MailMessage message, bool isSSL,string sysId)
{
SmtpClient smtp = new SmtpClient();
smtp.Host = hostName;
smtp.Port = portNumber;
smtp.Credentials = nwkCredential;
if (isSSL)
{
smtp.UseDefaultCredentials = (isSSL) ? false : true;
smtp.EnableSsl = isSSL;
}
//try
//{
// smtp.Send(message);
//}
//catch( Exception ex)
//{
//}
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = String.Format("{0}|{1}", message.To[0].User, sysId);
smtp.SendAsync(message, userState);
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
int _idx = token.IndexOf("|");
string _userName = token.Substring(0, _idx-1);
string _rId = token.Substring(_idx + 1, token.Length - (_idx + 1));
if (e.Cancelled)
{
if (System.Configuration.ConfigurationManager.AppSettings["FileCreateTag"] == "1")
CreatLogFile(String.Format("sending mail to {0} has been cancelled at {1}", _userName, DateTime.Now.ToString("dd/MMM/yyyy hh:mm:ss")));
}
if (e.Error != null)
{
if (System.Configuration.ConfigurationManager.AppSettings["FileCreateTag"] == "1")
CreatLogFile(String.Format("Mail has not been sent to {0} at {1} and Error {2}", _userName, DateTime.Now.ToString("dd/MMM/yyyy hh:mm:ss"), e.Error.ToString()));
int execSuccess = ExecuteQuery(string.Format("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='{0}' WHERE MQ_ID='{1}'", e.Error.ToString(), _rId));
//Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
}
else
{
//CreatLogFile(String.Format("Mail has been sent to {0} at {1}",token,DateTime.Now.ToString("dd/MMM/yyyy hh:mm:ss")));
int execSuccess = ExecuteQuery(string.Format("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Sent' WHERE MQ_ID='{0}'", token));
}
}
public void SendAsyncEmail()
{
//string con = GetHRMSConnection();
DataSet _dsMailQueue = GetTOPNRecords();
#region Log DataSet Count
if (_errorLogTag == "1")
{
if(_dsMailQueue != null)
if(_dsMailQueue.Tables.Count >0)
if(_dsMailQueue.Tables[0].Rows.Count>0)
MakeEntryInEventLog(_dsMailQueue.Tables[0].Rows.Count, "SendAsyncMail", String.Empty);
}
#endregion
string mailMessage;
if (_dsMailQueue != null)
{
foreach (DataRow _drMailQueue in _dsMailQueue.Tables[0].Rows)
{
//start:
try
{
mailMessage = _drMailQueue["MQ_Body"].ToString();
string MailFrom = System.Configuration.ConfigurationManager.AppSettings["mailFrom"];
string MailReplyTo = System.Configuration.ConfigurationManager.AppSettings["mailReplyTo"];
string MailFromPwd = System.Configuration.ConfigurationManager.AppSettings["mailFromPwd"];
string DisplayName = System.Configuration.ConfigurationManager.AppSettings["DisplayName"];
string MailTo = _drMailQueue["MQ_Recipient"].ToString();
string MailSubject = _drMailQueue["MQ_Subject"].ToString();
string MailMessage = mailMessage;
string smtpserver = System.Configuration.ConfigurationManager.AppSettings["smtpserver"];
string Port = System.Configuration.ConfigurationManager.AppSettings["port"];
string EnableSSL = System.Configuration.ConfigurationManager.AppSettings["enablessl"];
string DomainName = System.Configuration.ConfigurationManager.AppSettings["DomainName"];
string UserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
if (IsEmail(MailTo)) //proceed in case of valid Email Address
{
MailMessage mail = new MailMessage();
mail.To.Add(MailTo);
//mail.ReplyTo = new MailAddress(MailReplyTo, DisplayName);
mail.From = new MailAddress(MailFrom, DisplayName);
mail.Subject = MailSubject;
mail.Body = mailMessage;
mail.IsBodyHtml = true;
//System.Net.NetworkCredential basicAuthenticationInfo;
//if (!string.IsNullOrEmpty(DomainName))
// basicAuthenticationInfo = new System.Net.NetworkCredential(UserName, MailFromPwd, DomainName);
//else
//{
// UserName = MailFrom;
// basicAuthenticationInfo = new System.Net.NetworkCredential(UserName, MailFromPwd);
//}
//SmtpClient smtp = new SmtpClient(smtpserver);
#region Log DataSet Count
if (_errorLogTag == "1")
{
//EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
//oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
//oEventLogHelper.PageName = "EmailService.cs"; //page name
//oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
//oEventLogHelper.MethodName = "Make Smtp object"; //Method prototype
//string _dsmsgs = String.Format("Check Smtp Method created = {0}",smtpserver);
//oEventLogHelper.Message = _dsmsgs;
//oEventLogHelper.createEventLogForInformation();
//oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
//oEventLogHelper = null;
MakeEntryInEventLog(null, "Make Smtp object", String.Format("Check Smtp Method created = {0}", smtpserver));
}
#endregion
//if (EnableSSL.ToLower() == "Yes".ToLower())
//{
// smtp.EnableSsl = true;
// smtp.UseDefaultCredentials = false;
//}
//else
//{
// smtp.EnableSsl = false;
// smtp.UseDefaultCredentials = true;
//}
//smtp.Credentials = basicAuthenticationInfo;
//mail.IsBodyHtml = true;
//smtp.Port = int.Parse(Port);
//smtp.Send(mail);
// ConfigureNetworkCredntials(DomainName, UserName, MailFromPwd);
ConfigureSMTP(smtpserver, int.Parse(Port), ConfigureNetworkCredntials(DomainName, UserName, MailFromPwd), mail, (EnableSSL.ToLower().Equals("yes")) ? true : false, _drMailQueue["MQ_ID"].ToString());
// Update Mail status
// int execSuccess = ExecuteQuery(string.Format("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Sent' WHERE MQ_ID='{0}'", _drMailQueue["MQ_ID"]));
// End
}
else
{
// Update Mail status
int execSuccess = ExecuteQuery(string.Format("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Wrong Email Address' WHERE MQ_ID='{0}'", _drMailQueue["MQ_ID"]));
// End
}
}
catch (Exception ex)
{
//int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='Error' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
int execSuccess = ExecuteQuery("UPDATE ADMIN_MAILQUEUE SET MQ_STATUS='" + ex.Message.ToString() + " - " + ex.InnerException.ToString().Replace("'", "''") + "' WHERE MQ_ID='" + _drMailQueue["MQ_ID"].ToString() + "' ");
//goto start;
}
}
}
}
void CreatLogFile(string ex)
{
try
{
string _path = System.Configuration.ConfigurationManager.AppSettings["ErroLogFilePath"];
string filePath = _path + "EmailServiceErrorLog.txt";
if (File.Exists(filePath))
{
FileInfo _finfo = new FileInfo(filePath);
if (_finfo.Length < long.Parse(System.Configuration.ConfigurationManager.AppSettings["FileMaxSize"]))
{
AppendLogFile(filePath, ex);
}
else
{
CreateNewLogFile(filePath, ex);
}
}
else
{
CreateNewLogFile(filePath, ex);
}
}
catch (Exception exp)
{
MakeEntryInEventLog(null,"CreatLogFile",String.Format("Error at creating File : {0}", exp.Message));
}
}
void CreateNewLogFile(string filePath, string stringToWrite)
{
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine(stringToWrite);
sw.Flush();
sw.Close();
}
}
void AppendLogFile(string filePath, string stringToWrite)
{
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(stringToWrite);
sw.Flush();
sw.Close();
}
}
void MakeEntryInEventLog(int? recordsCount,string methodName, string message)
{
EventLogHelper oEventLogHelper = new EventLogHelper(); //instantiate class you can put this in using clause as well
oEventLogHelper.ApplicationName = "SHMA Email Service"; //Application name
oEventLogHelper.PageName = "EmailService.cs"; //page name
oEventLogHelper.NameSpace = "SHMA.EventLogHelper.Program"; //namespace till class name
oEventLogHelper.MethodName = methodName;// "SendEmail";
string _dsmsgs = string.Empty;//Method prototype
if (recordsCount != null)
{
if (recordsCount.HasValue)
_dsmsgs = String.Format("Select Top 10 rows --> received : {0}", recordsCount.Value);
else
_dsmsgs = "Select Top 10 rows --> Dataset is null in case of getting 10 records from table cause error.";
}
else
_dsmsgs = message;
oEventLogHelper.Message = _dsmsgs;
oEventLogHelper.createEventLogForInformation();
oEventLogHelper.Dispose(); //when finished with Event loging dispose it (dispose nulls all the internal objects and fields)
oEventLogHelper = null;
}
#endregion
}
}