Skip to content

Instantly share code, notes, and snippets.

@zwang
Created August 3, 2012 14:59
Show Gist options
  • Save zwang/3248410 to your computer and use it in GitHub Desktop.
Save zwang/3248410 to your computer and use it in GitHub Desktop.
Some functions using Send Grid to send emails
/// <summary>
/// Functions for sending emails using SendGrid
/// </summary>
public class SendGrid
{
#region Dependency and Initialization
private static SendingEmailSetting setting;
/// <summary>
/// This need to be set up when application starts
/// </summary>
/// <param name="set">The setting</param>
public static void InitializeSetting(SendingEmailSetting set)
{
setting = set;
}
#endregion
#region Send Email Using SendGrid
/// <summary>
/// Send Email out use SendGrid
/// </summary>
/// <param name="ID"></param>
/// <param name="toAddress"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="deliveryAttempts"></param>
/// <param name="replyToAddress"></param>
/// <returns></returns>
public static bool SendEmail(Guid ID, string toAddress, string subject, string body, List<string> categories, ref int deliveryAttempts, string replyToAddress = "help@company.com")
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string fromEmail = setting.FromEmail;
int maximumDeliveryAttempts = setting.EmailDeliveryMaxAttemps;
if (deliveryAttempts >= maximumDeliveryAttempts || IsEmailInBounceList(toAddress) || IsEmailInInvalidEmailList(toAddress)
|| IsEmailInSpamReport(toAddress) || IsEmailInUnsubscribeList(toAddress) || toAddress.EndsWith("-removed"))
{
deliveryAttempts = -1;
TraceInformation(string.Format("Email sending attempts reached limit or it is on the no sending list. ID: {0}. EmailAddress: {1}", ID.ToString(), toAddress));
return false;
}
else
{
try
{
return SendEmailBase(toAddress, subject, body, replyToAddress, sendGridAPIKey, sendGridPassword, fromEmail, categories);
}
catch (Exception ex)
{
TraceError(string.Format("SendGrid.SendEmail Exception. ID: {0}. ToEmail: {1}. ex: {2}", ID.ToString(), toAddress, ex.Message), ex);
return false;
}
}
}
/// <summary>
/// Simplified function for sending email directly.
/// </summary>
/// <param name="toAddress"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="replyToAddress"></param>
/// <returns></returns>
public static bool SendEmailSimple(string toAddress, string subject, string body, List<string> categories, string replyToAddress = "")
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string fromEmail = setting.FromEmail;
try
{
return SendEmailBase(toAddress, subject, body, replyToAddress, sendGridAPIKey, sendGridPassword, fromEmail, categories);
}
catch (Exception ex)
{
TraceError(string.Format("SendGrid.SendEmail Exception. Subject: {0}. ToAddress: {1}.", subject, toAddress), ex);
return false;
}
}
public static bool SendEmailBase(string toAddress, string subject, string body, string replyToAddress, string sendGridAPIKey, string sendGridPassword, string fromEmail, List<string> categories)
{
string header = "";
if (categories != null && categories.Count == 1)
{
header = "{\"category\":\"" + categories[0] + "\"}";
}
else
{
StringBuilder sb = new StringBuilder("{\"category\":[\"");
if (categories != null && categories.Count > 0)
{
for (int i = 0; i < categories.Count; i++)
{
sb.Append(categories[i]);
if (i != categories.Count - 1)
{
sb.Append("\",\"");
}
}
sb.Append("\"]}");
header = sb.ToString();
}
}
MailMessage mailMsg = new MailMessage();
//Categories for SendGrid
if (!string.IsNullOrWhiteSpace(header))
{
mailMsg.Headers.Add("X-SMTPAPI", header);
}
// To
mailMsg.To.Add(new MailAddress(toAddress));
// From
mailMsg.From = new MailAddress(fromEmail, "CompanyName");
if (replyToAddress != "")
{
mailMsg.ReplyToList.Add(new MailAddress(replyToAddress));
}
// Subject and multipart/alternative Body
mailMsg.Subject = subject;
string html = body;
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
//mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
// Init SmtpClient and send
SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(sendGridAPIKey, sendGridPassword);
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
return true;
}
/// <summary>
/// Send Email out use SendGrid
/// </summary>
/// <param name="ID"></param>
/// <param name="toAddress"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="deliveryAttempts"></param>
/// <param name="replyToAddress"></param>
/// <returns></returns>
public static bool SendEmailForNewsLetter(Guid ID, string toAddress, string subject, string body, List<string> categories, ref int deliveryAttempts, string replyToAddress = "")
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string fromEmail = setting.FromEmail;
int maximumDeliveryAttempts = setting.EmailDeliveryMaxAttemps;
if (deliveryAttempts >= maximumDeliveryAttempts || IsEmailInBounceList(toAddress) || IsEmailInInvalidEmailList(toAddress)
|| IsEmailInSpamReport(toAddress) || IsEmailInUnsubscribeList(toAddress) || toAddress.EndsWith("-removed"))
{
deliveryAttempts = -1;
TraceInformation(string.Format("Email sending attempts reached limit or it is on the no sending list. ID: {0}. EmailAddress: {1}", ID.ToString(), toAddress));
return false;
}
else
{
try
{
return SendEmailBase(toAddress, subject, body, replyToAddress, sendGridAPIKey, sendGridPassword, fromEmail, categories);
}
catch (Exception ex)
{
TraceError("SendGrid.SendEmail Exception. ID: " + ID.ToString() + ";" + ex.Message, ex);
return false;
}
}
}
#endregion
/// <summary>
/// Add Email address to unsubscribe list
/// </summary>
/// <param name="emailAddress">email address to delete</param>
/// <returns><c>true</c> if email is successfully added to the list, otherwise <c>false</c></returns>
public static bool AddEmailToUnsubscribeList(string emailAddress)
{
emailAddress = emailAddress.ToLower();
if (IsEmailInUnsubscribeList(emailAddress))
{
//Email already exist in the unsubscribe list
return true;
}
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/unsubscribes.add.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//Return – Success: [{"message":"success"}]
//Return – Error: {"message":"error","errors":[..."error messages"...]}
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
JObject result = JObject.Parse(resultStr);
string message = (string)result["message"];
if (message.ToLower() == "success")
{
return true;
}
else
{
TraceWarning(string.Format("SendGrid.AddEmailToUnsubscribeList. Email: {0}.", emailAddress), result);
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.AddEmailToUnsubscribeList Error", ex);
return false;
}
}
/// <summary>
/// Delete the email address from unsubscribe List
/// </summary>
/// <param name="emailAddress">email address to delete</param>
/// <returns><c>true</c> if email is successfully delete, otherwise <c>false</c></returns>
public static bool DeleteEmailFromUnsubscribeList(string emailAddress)
{
if (!IsEmailInUnsubscribeList(emailAddress))
{
//Email not exist in the unsubscribe list
return true;
}
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/unsubscribes.delete.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//Return – Success: [{"message":"success"}]
//Return – Error: [{"message":"error","errors":[..."error messages"...]}]
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
JObject result = JObject.Parse(resultStr);
string message = (string)result["message"];
if (message.ToLower() == "success")
{
return true;
}
else if (message.ToLower() == "email does not exist")
{
return true;
}
else
{
TraceWarning(string.Format("SendGrid.DeleteEmailFromUnsubscribeList Error: {0}. Email: {1}.", result, emailAddress));
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.AddEmailToUnsubscribeList Error", ex);
return false;
}
}
/// <summary>
/// Check if an email address is in the unsubscribe list of SendGrid
/// </summary>
/// <param name="emailAddress">email address to check</param>
/// <returns><c>true</c> if email is in the list, otherwise <c>false</c></returns>
public static bool IsEmailInUnsubscribeList(string emailAddress)
{
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/unsubscribes.get.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//If Email is in the unsubscribe list, then return the email address itself,
//otherwise return empty string if there is no error.
//If there is an error, return the error message
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
if (string.IsNullOrWhiteSpace(resultStr))
{
return false;
}
JObject result = JObject.Parse(resultStr);
string message = (string)result["email"];
if (message == emailAddress)
{
return true;
}
else
{
TraceWarning("SendGrid.IsEmailInUnsubscribeList Error: " + result);
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.IsEmailInUnsubscribeList Error", ex);
return false;
}
}
/// <summary>
/// Check if an email address is in the bounce list of SendGrid
/// </summary>
/// <param name="emailAddress">email address to check</param>
/// <returns><c>true</c> if email is in the list, otherwise <c>false</c></returns>
public static bool IsEmailInBounceList(string emailAddress)
{
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/bounces.get.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//If Email is in the unsubscribe list, then return the email address itself,
//otherwise return empty string if there is no error.
//If there is an error, return the error message
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
if (string.IsNullOrWhiteSpace(resultStr))
{
return false;
}
JObject result = JObject.Parse(resultStr);
string message = (string)result["email"];
if (message == emailAddress)
{
return true;
}
else
{
TraceWarning("SendGrid.IsEmailInBounceList Error: " + result);
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.IsEmailInBounceList Error", ex);
return false;
}
}
/// <summary>
/// Check if an email address is in the invalid Email list of SendGrid
/// </summary>
/// <param name="emailAddress">Email Address to check</param>
/// <returns><c>true</c> if email is in the list, otherwise <c>false</c></returns>
public static bool IsEmailInInvalidEmailList(string emailAddress)
{
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/invalidemails.get.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//If Email is in the unsubscribe list, then return the email address itself,
//otherwise return empty string if there is no error.
//If there is an error, return the error message
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
if (string.IsNullOrWhiteSpace(resultStr))
{
return false;
}
JObject result = JObject.Parse(resultStr);
string message = (string)result["email"];
if (message == emailAddress)
{
return true;
}
else
{
TraceWarning("SendGrid.IsEmailInInvalidEmailList Error: " + result);
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.IsEmailInInvalidEmailList Error", ex);
return false;
}
}
/// <summary>
/// Check if an email address is in the spam report email list of SendGrid
/// </summary>
/// <param name="emailAddress">Email Address to check</param>
/// <returns><c>true</c> if email is in the spam report list, otherwise <c>false</c></returns>
public static bool IsEmailInSpamReport(string emailAddress)
{
try
{
string sendGridAPIKey = setting.SendGridAPIKey;
string sendGridPassword = setting.SendGridAPIPassword;
string requestUri = string.Format("https://sendgrid.com/api/spamreports.get.json?api_user={0}&amp;api_key={1}&amp;email={2}", sendGridAPIKey, sendGridPassword, emailAddress);
// Create the web request
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//If Email is in the unsubscribe list, then return the email address itself,
//otherwise return empty string if there is no error.
//If there is an error, return the error message
string resultStr = reader.ReadToEnd().Trim();
resultStr = resultStr.Replace("[", "").Replace("]", "");
if (string.IsNullOrWhiteSpace(resultStr))
{
return false;
}
JObject result = JObject.Parse(resultStr);
string message = (string)result["email"];
if (message == emailAddress)
{
return true;
}
else
{
TraceWarning("SendGrid.IsEmailInSpamReport Error: " + result);
return false;
}
}
}
catch (Exception ex)
{
TraceError("SendGrid.IsEmailInSpamReport Error", ex);
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment