Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Data;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Web;
- using System.Threading;
- using System.Text.RegularExpressions;
- using System.Net.Mail;
- using System.ComponentModel;
- namespace Core.Web {
- /*
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <appSettings>
- <add key="smtpHost" value="smtp.???.com"/>
- <add key="smtpUser" value="???@??.com"/>
- <add key="smtpPassword" value="?????=="/>
- <add key="smtpIsPasswordEncrypted" value="True"/>
- <add key="smtpClientPort" value="0"/>
- <add key="smtpSSL" value="False"/>
- <add key="smtpCCUsers" value=""/>
- <add key="smtpBCCUsers" value=""/>
- <add key="smtpErrorOnNonValidAddresses" value="True"/>
- </appSettings>
- </configuration>
- */
- public class EmailHelper {
- public const string SMTP_HOST = "smtpHost";
- public const string SMTP_USER = "smtpUser";
- public const string SMTP_PASSWORD = "smtpPassword";
- public const string SMTP_ISPASSWORDENCRYPTED = "smtpIsPasswordEncrypted";
- public const string SMTP_CLIENTPORT = "smtpClientPort";
- public const string SMTP_SSL = "smtpSSL";
- public const string SMTP_CCUSERS = "smtpCCUsers";
- public const string SMTP_BCCUSERS = "smtpBCCUsers";
- public const string SMTP_ERROR_ON_NONVALID_ADDRESSES = "smtpErrorOnNonValidAddresses";
- #region Email Validation
- /// <summary>
- /// method for determining is the user provided a valid email address
- /// We use regular expressions in this check, as it is a more thorough
- /// way of checking the address provided
- /// </summary>
- /// <param name="email">email address to validate</param>
- /// <returns>true is valid, false if not valid</returns>
- public static bool IsValidEmail(string email) {
- return IsValidEmail(email,false);
- }
- public static bool IsValidEmail(string email,bool throwIfNotValid) {
- bool valid = false;
- if(IsTrimNull(email)) {
- valid = false;
- }
- else {
- //regular expression pattern for valid email
- //addresses, allows for the following domains:
- //com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
- string pattern = @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.
- (com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
- //Regular expression object
- Regex check = new Regex(pattern,RegexOptions.IgnorePatternWhitespace);
- //make sure an email address was provided
- if(string.IsNullOrEmpty(email))
- valid = false;
- else {
- //use IsMatch to validate the address
- valid = check.IsMatch(email);
- }
- }
- //return the value to the calling method
- if(!valid && throwIfNotValid)
- throw new InvalidEmailAddressException(email + " is not a valid email address");
- return valid;
- }
- static bool IsTrimNull(string value) {
- if(string.IsNullOrEmpty(value))
- return true;
- if(string.IsNullOrEmpty(value.Trim()))
- return true;
- return false;
- }
- #endregion
- public static void SendEmail(EmailParameter p) {
- SendEmail(p,false);
- }
- public static void SendEmail(EmailParameter p,bool async) {
- doSendEmail(p.PortalID,p.From,p.To.ToArray(),p.Cc.ToArray(),p.Bcc.ToArray(),p.Subject,p.Body,p.IsBodyHtml,p.Attachments.ToArray(),true,async,null);
- }
- public static System.Net.Mail.SmtpClient SendEmailAsync(EmailParameter p,Action<AsyncCompletedEventArgs> asyncCompleted) {
- return doSendEmail(p.PortalID,p.From,p.To.ToArray(),p.Cc.ToArray(),p.Bcc.ToArray(),p.Subject,p.Body,p.IsBodyHtml,p.Attachments.ToArray(),true,true,asyncCompleted);
- }
- static System.Net.Mail.SmtpClient doSendEmail(
- int portalID,
- string from,
- string[] to,
- string[] cc,
- string[] bcc,
- string subject,
- string body,
- bool isbodyHtml,
- Attachment[] attachments,
- bool throwError,
- bool async,
- Action<AsyncCompletedEventArgs> asyncCompleted) {
- try {
- bool smtpSSL = false;
- bool smtpIsPasswordEncrypted = false;
- int smtpClientPort = 0;
- string smtpHost = ConfigurationManager.AppSettings[SMTP_HOST];
- string smtpUser = ConfigurationManager.AppSettings[SMTP_USER];
- string smtpPassword = ConfigurationManager.AppSettings[SMTP_PASSWORD];
- bool smtpErrorOnNonValidAddresses = true;
- string formatType = "Text";
- if(isbodyHtml)
- formatType = "Html";
- if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_ISPASSWORDENCRYPTED]))
- bool.TryParse(ConfigurationManager.AppSettings[SMTP_ISPASSWORDENCRYPTED],out smtpIsPasswordEncrypted);
- if(smtpIsPasswordEncrypted) {
- if(!IsTrimNull(smtpPassword)) {
- string tempsmtpPassword = smtpPassword;
- try {
- smtpPassword = Encryption.Decrypt(smtpPassword);
- }
- catch {
- smtpPassword = tempsmtpPassword;
- }
- }
- }
- if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_CLIENTPORT])) {
- if(!int.TryParse(ConfigurationManager.AppSettings[SMTP_CLIENTPORT],out smtpClientPort))
- throw new ConfigurationErrorsException("Setting 'smtpClientPort' is invalid; setting must be an integer");
- }
- if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_SSL])) {
- if(!bool.TryParse(ConfigurationManager.AppSettings[SMTP_SSL],out smtpSSL))
- throw new ConfigurationErrorsException("Setting 'smtpSSL' is invalid; setting must be the type boolean; value is currenly '" + ConfigurationManager.AppSettings[SMTP_SSL] + "'");
- }
- string errorFormat = "Setting '{0}' is required to send email in AH.EmailHelper class";
- if(IsTrimNull(smtpHost))
- throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_HOST));
- if(smtpSSL) {
- if(IsTrimNull(smtpUser))
- throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_USER));
- if(IsTrimNull(smtpPassword))
- throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_PASSWORD));
- }
- if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_ERROR_ON_NONVALID_ADDRESSES]))
- bool.TryParse(ConfigurationManager.AppSettings[SMTP_ERROR_ON_NONVALID_ADDRESSES],out smtpErrorOnNonValidAddresses);
- //Validate email addresses
- List<string> tempTo = new List<string>();
- foreach(string address in to) {
- if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
- tempTo.Add(address);
- }
- to = tempTo.ToArray();
- if(to.Length == 0)
- throw new EmailAddressException("There must be at least '1' to email address");
- //additional CC From Web.config
- string smtpCcUsers = ConfigurationManager.AppSettings[SMTP_CCUSERS];
- if(!IsTrimNull(smtpCcUsers)) {
- string[] splitValues = smtpCcUsers.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
- List<string> additionalCC = new List<string>();
- foreach(string address in splitValues) {
- if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
- additionalCC.Add(address);
- }
- cc = additionalCC.ToArray();
- }
- List<string> modBcc = new List<string>();
- //additional BCC From Web.config
- string smtpBccUsers = ConfigurationManager.AppSettings[SMTP_BCCUSERS];
- if(!IsTrimNull(smtpBccUsers)) {
- string[] splitValues = smtpBccUsers.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
- foreach(string address in splitValues) {
- if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
- modBcc.Add(address);
- }
- }
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.From = new System.Net.Mail.MailAddress(from);
- message.Subject = subject;
- message.Body = body;
- if(attachments != null) {
- foreach(Attachment item in attachments)
- message.Attachments.Add(item);
- }
- foreach(string address in to)
- message.To.Add(address);
- foreach(string address in cc)
- message.CC.Add(address);
- if(modBcc.Count > 0) {
- foreach(string b in modBcc)
- message.Bcc.Add(b);
- }
- if(formatType.Equals("Html",StringComparison.CurrentCultureIgnoreCase))
- message.IsBodyHtml = true;
- else
- message.IsBodyHtml = false;
- System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
- smtpClient.Host = smtpHost;
- if(smtpClientPort > 0)
- smtpClient.Port = smtpClientPort;
- if(!string.IsNullOrEmpty(smtpUser)) {
- smtpClient.Credentials = new System.Net.NetworkCredential(smtpUser,smtpPassword);
- smtpClient.EnableSsl = smtpSSL;
- }
- if(async) {
- if(asyncCompleted != null) {
- smtpClient.SendCompleted += (s,e) => {
- if(asyncCompleted != null)
- asyncCompleted(e);
- };
- }
- smtpClient.SendAsync(message,null);
- }
- else {
- smtpClient.Send(message);
- }
- return smtpClient;
- }
- catch {
- if(throwError)
- throw;
- return null;
- }
- }
- }
- public class EmailParameter {
- public int PortalID { get; set; }
- public string From { get; set; }
- public List<string> To { get; private set; }
- public List<string> Cc { get; private set; }
- public List<string> Bcc { get; private set; }
- public string Subject { get; set; }
- public string Body { get; set; }
- public bool IsBodyHtml { get; set; }
- public List<Attachment> Attachments { get; private set; }
- public EmailParameter() {
- this.PortalID = 1;
- this.To = new List<string>();
- this.Cc = new List<string>();
- this.Bcc = new List<string>();
- this.Attachments = new List<Attachment>();
- }
- public void ToAdd(string address) {
- this.To.Add(address);
- }
- public void BccAdd(string address) {
- this.Bcc.Add(address);
- }
- }
- [global::System.Serializable]
- public class InvalidEmailAddressException:EmailAddressException {
- public InvalidEmailAddressException() {
- }
- public InvalidEmailAddressException(string message)
- : base(message) {
- }
- public InvalidEmailAddressException(string message,Exception inner)
- : base(message,inner) {
- }
- protected InvalidEmailAddressException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info,context) {
- }
- }
- [global::System.Serializable]
- public class EmailAddressException:ApplicationException {
- public EmailAddressException() { }
- public EmailAddressException(string message) : base(message) { }
- public EmailAddressException(string message,Exception inner) : base(message,inner) { }
- protected EmailAddressException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info,context) { }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment