CEL_Payroll/Payroll.BO/Mail/MailSender.cs

543 lines
20 KiB
C#
Raw Permalink Normal View History

2024-09-17 14:30:13 +06:00
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using Ease.CoreV35;
using Ease.CoreV35.Model;
using Ease.CoreV35.Caching;
using System.Data.Linq.Mapping;
using System.Text.RegularExpressions;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net.Mime;
using System.IO;
//using Microsoft.Exchange.WebServices;
//using Microsoft.Exchange.WebServices.Data;
namespace Payroll.BO
{
public class MailSender
{
private SmtpClient client = null;
private object _mailbody;
public object Mailbody
{
get { return _mailbody; }
set { _mailbody = value; }
}
#region Private Variable
private string _from;
private string _to;
private string _cc;
private string _subject;
private string _body;
private string _attachments;
private string _link;
#endregion
#region Event
public event EventHandler client_SendCompleted;
#endregion
#region Constractor
public MailSender()
{
_to = "";
_cc = "";
_body = "";
_subject = "";
_attachments = "";
_from = "";
_link = "";
}
#endregion
#region Properties
public string CC
{
get { return _cc; }
set { _cc = value; }
}
public string From
{
get { return _from; }
set { _from = value; }
}
public string To
{
get { return _to; }
set { _to = value; }
}
public string Subject
{
get { return _subject; }
set { _subject = value; }
}
public string Body
{
get { return _body; }
set { _body = value; }
}
public string Link
{
get { return _link; }
set { _link = value; }
}
public string Attachments
{
get { return _attachments; }
set { _attachments = value; }
}
#endregion
#region Methods
//public EnumSendMail SendMailNovartisUsingExchangeService()
//{
// //Mail Sending using Exchange Service
// try
// {
// if (_to == "")
// {
// return EnumSendMail.ToMissing;
// }
// else if (_subject == "")
// {
// return EnumSendMail.SubjectMissing;
// }
// else if (_body == "")
// {
// return EnumSendMail.BodyMissing;
// }
// //List<string> attachment = new List<string>();
// //if (_fileAttachmentPath.Length > 0)
// //{
// // attachment.AddRange(new string[] { _fileAttachmentPath });
// //}
// //_body += AddLink();
// //System.Net.Mail.Attachment attachFile = new System.Net.Mail.Attachment(_fileAttachmentPath);
// //MyMessage.Attachments.Add(attachFile);
// string To = _to;
// string From = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("FromAddress");
// string userName = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("UserID");
// string password = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("Password");
// string sServer = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EmailServer");
// string sPort = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("PortNumber");
// int portNumber = Convert.ToInt32(sPort);
// //MailMessage mail = new MailMessage();
// //mail.To.Add(To);
// //mail.Subject = _subject;
// //mail.Body = _body;
// //mail.Attachments.Add(attachFile);
// //mail.From = new MailAddress(From);
// //mail.IsBodyHtml = true;
// //SmtpClient oClient = new SmtpClient(sServer, portNumber);
// //oClient.EnableSsl = false;
// //oClient.UseDefaultCredentials = false;
// //oClient.Credentials = new System.Net.NetworkCredential(userName, password);
// //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// //oClient.Send(mail);
// ExchangeService service = new ExchangeService();
// //Autodis
// //ExchangeService
// //Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverRedirectionUrlValidationCallback abc = new Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverRedirectionUrlValidationCallback(Test);
// service.Credentials = new NetworkCredential(userName, password);
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// try
// {
// service.AutodiscoverUrl(From);
// }
// catch (Exception ex)
// {
// service.AutodiscoverUrl(From, (calbackURL) => calbackURL.Trim().ToLower().StartsWith("https://"));
// }
// EmailMessage message = new EmailMessage(service);
// message.Subject = _subject;
// message.Body = new MessageBody(_body);
// message.From = new EmailAddress(From);
// message.ToRecipients.Add(To);
// if (string.IsNullOrEmpty(Attachments))
// message.Attachments.AddFileAttachment(Attachments);
// message.Send();
// //message.SendAndSaveCopy();
// }
// catch (Exception ex)
// {
// throw new ServiceException(ex.ToString());
// //EnumSendMail.SendError;
// }
// return EnumSendMail.SuccessFullySend;
//}
public EnumSendMail SendMail()
{
EnumSendMail sendStatus = EnumSendMail.SuccessFullySend;
try
{
string sServer = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EmailServer");
string userID = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("UserID");
string checkSendMail = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("SendMethod");
string password = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("Password");
string PortNumber = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("PortNumber");
string CheckSSL = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EnableSSL");
string EWSUrl = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EWSEndpoint");
password = Ease.CoreV35.Utility.Global.CipherFunctions.Decrypt("Cel.Admin", password);
_body += AddLink();
_from = _from == "" ? Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("FromAddress") : _from;
if (string.IsNullOrEmpty(_from))
{
return EnumSendMail.FromMissing;
}
if (string.IsNullOrEmpty(_to))
{
return EnumSendMail.ToMissing;
}
if (checkSendMail.ToUpper() == "SMTP")
{
MailMessage mailMessage = null;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
client = new SmtpClient(sServer, PortNumber != string.Empty ? Convert.ToInt32(PortNumber) : 25);
client.EnableSsl = CheckSSL.ToUpper() == "YES" ? true : false;
if (sServer.Length > 0)
{
client.UseDefaultCredentials = true;
if (userID != "" && password != "")
{
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(userID, password);
}
mailMessage = new MailMessage(_from, _to, _subject, _body);
mailMessage.IsBodyHtml = true;
if (_cc.Length > 0) { mailMessage.CC.Add(_cc); }
if (_attachments.Length > 0) { mailMessage.Attachments.Add(new System.Net.Mail.Attachment(_attachments)); }
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
client.Send(mailMessage);
mailMessage.Dispose();
}
}
//else if (Enum.IsDefined(typeof(ExchangeVersion), checkSendMail))
//{
// ExchangeVersion enmExchangeVersion = (ExchangeVersion)Enum.Parse(typeof(ExchangeVersion), checkSendMail);
// ExchangeService oService = new ExchangeService(enmExchangeVersion);
// EmailMessage oMessage;
// //oService.AutodiscoverUrl(_from, delegate { return true; });
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// oService.UseDefaultCredentials = true;
// if (userID != "" && password != "")
// {
// oService.UseDefaultCredentials = false;
// oService.Credentials = new NetworkCredential(userID, password, sServer);
// }
// if (EWSUrl != string.Empty)
// {
// oService.Url = new Uri(EWSUrl);
// }
// else
// {
// try
// {
// oService.AutodiscoverUrl(_from);
// }
// catch (Exception)
// {
// oService.AutodiscoverUrl(_from, (calbackURL) => calbackURL.Trim().ToLower().StartsWith("https://"));
// }
// }
// oMessage = new EmailMessage(oService);
// oMessage.Subject = _subject;
// oMessage.Body = _body;
// oMessage.ToRecipients.Add(_to);
// oMessage.From = new EmailAddress(_from);
// if (!string.IsNullOrEmpty(_attachments))
// oMessage.Attachments.AddFileAttachment(Attachments);
// oMessage.Send();
//}
}
catch (Exception ex)
{
//StringBuilder sb = new StringBuilder();
//sb.Append(ex.Message);
//Exception innerException = ex.InnerException;
//while (innerException != null)
//{
// sb.Append("--> inner Exception: ");
// sb.Append(innerException.Message);
// innerException = innerException.InnerException;
//}
//throw new MailSenderException(sb.ToString());
sendStatus = EnumSendMail.SendError;
}
return sendStatus;
}
//public void SendMail2()
//{
// try
// {
// string sServer = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EmailServer");
// string userID = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("UserID");
// string checkSendMail = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("SendMethod");
// string password = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("Password");
// string PortNumber = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("PortNumber");
// string CheckSSL = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EnableSSL");
// string EWSUrl = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EWSEndpoint");
// //password = Ease.CoreV35.Utility.Global.CipherFunctions.Decrypt("Cel.Admin" , password);
// _body += AddLink();
// _from = _from == "" ? Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("FromAddress") : _from;
// if (checkSendMail.ToUpper() == "SMTP")
// {
// MailMessage mailMessage = null;
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// client = new SmtpClient(sServer, PortNumber != string.Empty ? Convert.ToInt32(PortNumber) : 25);
// client.EnableSsl = CheckSSL.ToUpper() == "YES" ? true : false;
// if (sServer.Length > 0)
// {
// client.UseDefaultCredentials = true;
// if (userID != "" && password != "")
// {
// client.UseDefaultCredentials = false;
// client.Credentials = new System.Net.NetworkCredential(userID, password);
// }
// mailMessage = new MailMessage(_from, _to, _subject, _body);
// mailMessage.IsBodyHtml = true;
// if (_cc.Length > 0) { mailMessage.CC.Add(_cc); }
// if (_attachments.Length > 0) { mailMessage.Attachments.Add(new System.Net.Mail.Attachment(_attachments)); }
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// client.Send(mailMessage);
// }
// }
// else if (Enum.IsDefined(typeof(ExchangeVersion), checkSendMail))
// {
// ExchangeVersion enmExchangeVersion = (ExchangeVersion)Enum.Parse(typeof(ExchangeVersion), checkSendMail);
// ExchangeService oService = new ExchangeService(enmExchangeVersion);
// EmailMessage oMessage;
// //oService.AutodiscoverUrl(_from, delegate { return true; });
// ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// oService.UseDefaultCredentials = true;
// if (userID != "" && password != "")
// {
// oService.UseDefaultCredentials = false;
// oService.Credentials = new NetworkCredential(userID, password, sServer);
// }
// if (EWSUrl != string.Empty)
// {
// oService.Url = new Uri(EWSUrl);
// }
// else
// {
// try
// {
// oService.AutodiscoverUrl(_from);
// }
// catch (Exception)
// {
// oService.AutodiscoverUrl(_from, (calbackURL) => calbackURL.Trim().ToLower().StartsWith("https://"));
// }
// }
// oMessage = new EmailMessage(oService);
// oMessage.Subject = _subject;
// oMessage.Body = _body;
// oMessage.ToRecipients.Add(_to);
// oMessage.From = new EmailAddress(_from);
// if (!string.IsNullOrEmpty(_attachments))
// oMessage.Attachments.AddFileAttachment(Attachments);
// oMessage.Send();
// }
// }
// catch (Exception ex)
// {
// StringBuilder sb = new StringBuilder();
// sb.Append(ex.Message);
// Exception innerException = ex.InnerException;
// while (innerException != null)
// {
// sb.Append("--> inner Exception: ");
// sb.Append(innerException.Message);
// innerException = innerException.InnerException;
// }
// throw new MailSenderException(sb.ToString());
// }
//}
public static void SendLHEmail(string emailTo, string emailFrom, string subject, string emailBody)
{
System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
mail.From = emailFrom;
mail.Subject = subject;
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
mail.Body = emailBody;
mail.To = emailTo;
System.Web.Mail.SmtpMail.SmtpServer = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("EmailServer");
System.Web.Mail.SmtpMail.Send(mail);
}
public void AddCC(string cc)
{
if (IsValidEmail(cc))
{
if (_cc == "")
_cc += cc;
else
_cc += cc + ";";
}
}
public void AddTo(string to)
{
if (IsValidEmail(to))
{
if (_to == "")
_to += to;
else
_to += to + ";";
}
}
public void AddAttachment(string attachment)
{
if (_attachments == "")
_attachments += attachment;
else
_attachments += attachment + ";";
}
public string AddLink()
{
if (_link.Length > 0)
{
//return ( Environment.NewLine + Environment.NewLine + Environment.NewLine +
// "<br>Please, click on the following link to take action." +
// Environment.NewLine + Environment.NewLine +
// "<a href=\"" + _link.ToString() + "\">Link</a> " +
// //"<" + _link.ToString() + ">" +
// Environment.NewLine + Environment.NewLine + Environment.NewLine +
// "<br><br><br><br>This is a computer generated mail. Please don't reply.<br>");
return (" Please, click on this " + _link.ToString() + " to take action." +
" This is a computer generated mail. Please don't reply.");
}
else
{
//return Environment.NewLine + Environment.NewLine + "<i>" + "This is a computer generated mail. Please don't reply." + "</i>";
return "";
}
}
public static bool IsValidEmail(string inputEmail)
{
int n1 = inputEmail.IndexOf("@");
int n2 = inputEmail.IndexOf(".");
int n4 = inputEmail.LastIndexOf(".");
int n3 = inputEmail.IndexOf(" ");
if (n3 > 0)
return false;
if (n2 < n4)
n2 = n4;
if (n1 < n2)
return true;
else
return false;
}
public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// replace with proper validation
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
else
return false;
}
#endregion
}
public class MailSenderException : Exception
{
public MailSenderException(string message)
: base("Failed to Send Mail due to:" + message)
{
}
public MailSenderException(string message, Exception innerException)
: base("Failed to Send Mail due to:" + message, innerException)
{
}
}
}