andrew4582

EmailHelper

Sep 24th, 2011
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.14 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Web;
  7. using System.Threading;
  8. using System.Text.RegularExpressions;
  9. using System.Net.Mail;
  10. using System.ComponentModel;
  11.  
  12. namespace Core.Web {
  13.     /*
  14. <?xml version="1.0" encoding="utf-8" ?>
  15. <configuration>
  16.   <appSettings>
  17.     <add key="smtpHost" value="smtp.???.com"/>
  18.     <add key="smtpUser" value="???@??.com"/>
  19.     <add key="smtpPassword" value="?????=="/>
  20.     <add key="smtpIsPasswordEncrypted" value="True"/>
  21.     <add key="smtpClientPort" value="0"/>
  22.     <add key="smtpSSL" value="False"/>
  23.     <add key="smtpCCUsers" value=""/>
  24.     <add key="smtpBCCUsers" value=""/>
  25.     <add key="smtpErrorOnNonValidAddresses" value="True"/>
  26.   </appSettings>
  27. </configuration>
  28.      */
  29.     public class EmailHelper {
  30.  
  31.         public const string SMTP_HOST = "smtpHost";
  32.         public const string SMTP_USER = "smtpUser";
  33.         public const string SMTP_PASSWORD = "smtpPassword";
  34.         public const string SMTP_ISPASSWORDENCRYPTED = "smtpIsPasswordEncrypted";
  35.         public const string SMTP_CLIENTPORT = "smtpClientPort";
  36.         public const string SMTP_SSL = "smtpSSL";
  37.         public const string SMTP_CCUSERS = "smtpCCUsers";
  38.         public const string SMTP_BCCUSERS = "smtpBCCUsers";
  39.         public const string SMTP_ERROR_ON_NONVALID_ADDRESSES = "smtpErrorOnNonValidAddresses";
  40.  
  41.  
  42.         #region Email Validation
  43.         /// <summary>
  44.         /// method for determining is the user provided a valid email address
  45.         /// We use regular expressions in this check, as it is a more thorough
  46.         /// way of checking the address provided
  47.         /// </summary>
  48.         /// <param name="email">email address to validate</param>
  49.         /// <returns>true is valid, false if not valid</returns>
  50.  
  51.         public static bool IsValidEmail(string email) {
  52.             return IsValidEmail(email,false);
  53.         }
  54.  
  55.         public static bool IsValidEmail(string email,bool throwIfNotValid) {
  56.             bool valid = false;
  57.  
  58.             if(IsTrimNull(email)) {
  59.                 valid = false;
  60.             }
  61.             else {
  62.                 //regular expression pattern for valid email
  63.                 //addresses, allows for the following domains:
  64.                 //com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
  65.                 string pattern = @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.
  66.    (com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
  67.                 //Regular expression object
  68.                 Regex check = new Regex(pattern,RegexOptions.IgnorePatternWhitespace);
  69.                 //make sure an email address was provided
  70.                 if(string.IsNullOrEmpty(email))
  71.                     valid = false;
  72.                 else {
  73.                     //use IsMatch to validate the address
  74.                     valid = check.IsMatch(email);
  75.                 }
  76.             }
  77.             //return the value to the calling method
  78.             if(!valid && throwIfNotValid)
  79.                 throw new InvalidEmailAddressException(email + " is not a valid email address");
  80.             return valid;
  81.         }
  82.  
  83.         static bool IsTrimNull(string value) {
  84.             if(string.IsNullOrEmpty(value))
  85.                 return true;
  86.             if(string.IsNullOrEmpty(value.Trim()))
  87.                 return true;
  88.             return false;
  89.         }
  90.  
  91.         #endregion
  92.  
  93.         public static void SendEmail(EmailParameter p) {
  94.             SendEmail(p,false);
  95.         }
  96.  
  97.         public static void SendEmail(EmailParameter p,bool async) {
  98.  
  99.             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);
  100.  
  101.         }
  102.         public static System.Net.Mail.SmtpClient SendEmailAsync(EmailParameter p,Action<AsyncCompletedEventArgs> asyncCompleted) {
  103.             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);
  104.         }
  105.  
  106.         static System.Net.Mail.SmtpClient doSendEmail(
  107.             int portalID,
  108.             string from,
  109.             string[] to,
  110.             string[] cc,
  111.             string[] bcc,
  112.             string subject,
  113.             string body,
  114.             bool isbodyHtml,
  115.             Attachment[] attachments,
  116.             bool throwError,
  117.             bool async,
  118.             Action<AsyncCompletedEventArgs> asyncCompleted) {
  119.             try {
  120.                 bool smtpSSL = false;
  121.                 bool smtpIsPasswordEncrypted = false;
  122.                 int smtpClientPort = 0;
  123.                 string smtpHost = ConfigurationManager.AppSettings[SMTP_HOST];
  124.                 string smtpUser = ConfigurationManager.AppSettings[SMTP_USER];
  125.                 string smtpPassword = ConfigurationManager.AppSettings[SMTP_PASSWORD];
  126.                 bool smtpErrorOnNonValidAddresses = true;
  127.  
  128.                 string formatType = "Text";
  129.                 if(isbodyHtml)
  130.                     formatType = "Html";
  131.  
  132.                 if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_ISPASSWORDENCRYPTED]))
  133.                     bool.TryParse(ConfigurationManager.AppSettings[SMTP_ISPASSWORDENCRYPTED],out smtpIsPasswordEncrypted);
  134.  
  135.                 if(smtpIsPasswordEncrypted) {
  136.                     if(!IsTrimNull(smtpPassword)) {
  137.                         string tempsmtpPassword = smtpPassword;
  138.                         try {
  139.                             smtpPassword = Encryption.Decrypt(smtpPassword);
  140.                         }
  141.                         catch {
  142.                             smtpPassword = tempsmtpPassword;
  143.                         }
  144.                     }
  145.                 }
  146.                 if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_CLIENTPORT])) {
  147.                     if(!int.TryParse(ConfigurationManager.AppSettings[SMTP_CLIENTPORT],out smtpClientPort))
  148.                         throw new ConfigurationErrorsException("Setting 'smtpClientPort' is invalid; setting must be an integer");
  149.                 }
  150.                 if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_SSL])) {
  151.                     if(!bool.TryParse(ConfigurationManager.AppSettings[SMTP_SSL],out smtpSSL))
  152.                         throw new ConfigurationErrorsException("Setting 'smtpSSL' is invalid; setting must be the type boolean; value is currenly '" + ConfigurationManager.AppSettings[SMTP_SSL] + "'");
  153.                 }
  154.                 string errorFormat = "Setting '{0}' is required to send email in AH.EmailHelper class";
  155.  
  156.                 if(IsTrimNull(smtpHost))
  157.                     throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_HOST));
  158.                 if(smtpSSL) {
  159.                     if(IsTrimNull(smtpUser))
  160.                         throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_USER));
  161.                     if(IsTrimNull(smtpPassword))
  162.                         throw new ConfigurationErrorsException(string.Format(errorFormat,SMTP_PASSWORD));
  163.                 }
  164.                 if(!IsTrimNull(ConfigurationManager.AppSettings[SMTP_ERROR_ON_NONVALID_ADDRESSES]))
  165.                     bool.TryParse(ConfigurationManager.AppSettings[SMTP_ERROR_ON_NONVALID_ADDRESSES],out smtpErrorOnNonValidAddresses);
  166.  
  167.                 //Validate email addresses
  168.                 List<string> tempTo = new List<string>();
  169.                 foreach(string address in to) {
  170.                     if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
  171.                         tempTo.Add(address);
  172.                 }
  173.                 to = tempTo.ToArray();
  174.                 if(to.Length == 0)
  175.                     throw new EmailAddressException("There must be at least '1' to email address");
  176.  
  177.                 //additional CC From Web.config
  178.                 string smtpCcUsers = ConfigurationManager.AppSettings[SMTP_CCUSERS];
  179.                 if(!IsTrimNull(smtpCcUsers)) {
  180.                     string[] splitValues = smtpCcUsers.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
  181.                     List<string> additionalCC = new List<string>();
  182.                     foreach(string address in splitValues) {
  183.                         if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
  184.                             additionalCC.Add(address);
  185.                     }
  186.                     cc = additionalCC.ToArray();
  187.                 }
  188.  
  189.                 List<string> modBcc = new List<string>();
  190.                 //additional BCC From Web.config
  191.                 string smtpBccUsers = ConfigurationManager.AppSettings[SMTP_BCCUSERS];
  192.                 if(!IsTrimNull(smtpBccUsers)) {
  193.                     string[] splitValues = smtpBccUsers.Split(",".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
  194.                     foreach(string address in splitValues) {
  195.                         if(IsValidEmail(address,smtpErrorOnNonValidAddresses))
  196.                             modBcc.Add(address);
  197.                     }
  198.                 }
  199.  
  200.                 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  201.                 message.From = new System.Net.Mail.MailAddress(from);
  202.                 message.Subject = subject;
  203.                 message.Body = body;
  204.                 if(attachments != null) {
  205.                     foreach(Attachment item in attachments)
  206.                         message.Attachments.Add(item);
  207.                 }
  208.                 foreach(string address in to)
  209.                     message.To.Add(address);
  210.  
  211.                 foreach(string address in cc)
  212.                     message.CC.Add(address);
  213.                 if(modBcc.Count > 0) {
  214.                     foreach(string b in modBcc)
  215.                         message.Bcc.Add(b);
  216.                 }
  217.                 if(formatType.Equals("Html",StringComparison.CurrentCultureIgnoreCase))
  218.                     message.IsBodyHtml = true;
  219.                 else
  220.                     message.IsBodyHtml = false;
  221.  
  222.                 System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
  223.                 smtpClient.Host = smtpHost;
  224.                 if(smtpClientPort > 0)
  225.                     smtpClient.Port = smtpClientPort;
  226.                 if(!string.IsNullOrEmpty(smtpUser)) {
  227.                     smtpClient.Credentials = new System.Net.NetworkCredential(smtpUser,smtpPassword);
  228.                     smtpClient.EnableSsl = smtpSSL;
  229.                 }
  230.                 if(async) {
  231.                     if(asyncCompleted != null) {
  232.                         smtpClient.SendCompleted += (s,e) => {
  233.                             if(asyncCompleted != null)
  234.                                 asyncCompleted(e);
  235.                         };
  236.                     }
  237.                     smtpClient.SendAsync(message,null);
  238.                 }
  239.                 else {
  240.                     smtpClient.Send(message);
  241.                 }
  242.  
  243.                 return smtpClient;
  244.             }
  245.             catch {
  246.                 if(throwError)
  247.                     throw;
  248.  
  249.                 return null;
  250.             }
  251.         }
  252.  
  253.     }
  254.  
  255.  
  256.     public class EmailParameter {
  257.         public int PortalID { get; set; }
  258.         public string From { get; set; }
  259.         public List<string> To { get; private set; }
  260.         public List<string> Cc { get; private set; }
  261.         public List<string> Bcc { get; private set; }
  262.         public string Subject { get; set; }
  263.         public string Body { get; set; }
  264.         public bool IsBodyHtml { get; set; }
  265.         public List<Attachment> Attachments { get; private set; }
  266.         public EmailParameter() {
  267.             this.PortalID = 1;
  268.             this.To = new List<string>();
  269.             this.Cc = new List<string>();
  270.             this.Bcc = new List<string>();
  271.             this.Attachments = new List<Attachment>();
  272.         }
  273.         public void ToAdd(string address) {
  274.             this.To.Add(address);
  275.         }
  276.         public void BccAdd(string address) {
  277.             this.Bcc.Add(address);
  278.         }
  279.     }
  280.  
  281.     [global::System.Serializable]
  282.     public class InvalidEmailAddressException:EmailAddressException {
  283.         public InvalidEmailAddressException() {
  284.         }
  285.         public InvalidEmailAddressException(string message)
  286.             : base(message) {
  287.         }
  288.         public InvalidEmailAddressException(string message,Exception inner)
  289.             : base(message,inner) {
  290.         }
  291.         protected InvalidEmailAddressException(
  292.           System.Runtime.Serialization.SerializationInfo info,
  293.           System.Runtime.Serialization.StreamingContext context)
  294.             : base(info,context) {
  295.         }
  296.     }
  297.  
  298.     [global::System.Serializable]
  299.     public class EmailAddressException:ApplicationException {
  300.         public EmailAddressException() { }
  301.         public EmailAddressException(string message) : base(message) { }
  302.         public EmailAddressException(string message,Exception inner) : base(message,inner) { }
  303.         protected EmailAddressException(
  304.           System.Runtime.Serialization.SerializationInfo info,
  305.           System.Runtime.Serialization.StreamingContext context)
  306.             : base(info,context) { }
  307.     }
  308. }
Advertisement
Add Comment
Please, Sign In to add comment