diff options
20 files changed, 1110 insertions, 450 deletions
diff --git a/SendGrid/Example/Program.cs b/SendGrid/Example/Program.cs index 87c44a4..c1815b7 100755 --- a/SendGrid/Example/Program.cs +++ b/SendGrid/Example/Program.cs @@ -11,69 +11,26 @@ namespace Example {
class Program
{
- static void Main(String[] args)
- {
- var restInstance = REST.GetInstance(new NetworkCredential("sgrid_username", "sgrid_password"));
-
- //create a new message object
- var message = SendGrid.GenerateInstance();
-
- message.AddTo("cj.buchmann@sendgrid.com");
- message.AddTo("tyler.bischel@sendgrid.com");
- message.AddTo("kyle.partridge@sendgrid.com");
- message.From = new MailAddress("cj.buchmann@sendgrid.com");
- message.Html = "<div>hello world</div>";
- message.Subject = "Hello World SUbject";
- message.AddAttachment(@"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg");
- message.AddAttachment(@"C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg");
-
- restInstance.Deliver(message);
-
- Console.WriteLine("Message Sent");
- Console.WriteLine("DONE!");
- Console.ReadLine();
- }
-
// this code is used for the SMTPAPI examples
- /*static void Main(string[] args)
+ static void Main(string[] args)
{
- var username = "cjbuchmann";
- var password = "gadget15";
+ var username = "sgrid_username";
+ var password = "sgrid_password";
var from = "cj.buchmann@sendgrid.com";
var to = new List<String>
{
"cj.buchmann@sendgrid.com"
};
- var bcc = new List<string>
- {
- "eric@sendgrid.com"
- };
-
- var cc = new List<string>
- {
- "eric@sendgrid.com"
- };
-
//initialize the SMTPAPI example class
var smtpapi = new SMTPAPI(username, password, from, to);
+ var restapi = new RESTAPI(username, password, from, to);
- //send a simple HTML encoded email.
- //smtpapi.SimpleHTMLEmail();
-
- //send a simple Plaintext email.
- //smtpapi.SimplePlaintextEmail();
-
- //send a gravatar enabled email.
- //smtpapi.EnableGravatarEmail();
-
- //send an open tracking enabled email.
- //smtpapi.EnableOpenTrackingEmail();
-
- //send an open tracking enabled email.
- smtpapi.EnableClickTrackingEmail();
+ //use this section to test out our REST and SMTP examples!
+ restapi.EnableTemplateEmail();
+ Console.WriteLine("Done!");
Console.ReadLine();
- }*/
+ }
}
}
diff --git a/SendGrid/Example/RESTAPI.cs b/SendGrid/Example/RESTAPI.cs index 73dbf04..8c15800 100755 --- a/SendGrid/Example/RESTAPI.cs +++ b/SendGrid/Example/RESTAPI.cs @@ -14,82 +14,412 @@ namespace Example private String _password;
private String _from;
private IEnumerable<String> _to;
- private IEnumerable<String> _bcc;
- private IEnumerable<String> _cc;
- public RESTAPI(String username, String password, String from, IEnumerable<String> recipients, IEnumerable<String> bcc, IEnumerable<String> cc)
+ public RESTAPI(String username, String password, String from, IEnumerable<String> recipients)
{
_username = username;
_password = password;
_from = from;
_to = recipients;
- _bcc = bcc;
- _cc = cc;
}
+ /// <summary>
+ /// Send a simple HTML based email
+ /// </summary>
public void SimpleHTMLEmail()
{
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ message.Html = "<html><p>Hello</p><p>World</p></html>";
+
+ //set the message subject
+ message.Subject = "Hello World HTML Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Send a simple Plain Text email
+ /// </summary>
+ public void SimplePlaintextEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ message.Text = "Hello World Plain Text";
+
+ //set the message subject
+ message.Subject = "Hello World Plain Text Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Enable The Gravatar Filter.
+ /// Currently the filter generates a 1x1 pixel gravatar image.
+ /// http://docs.sendgrid.com/documentation/apps/gravatar/
+ /// </summary>
+ public void EnableGravatarEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
- if(_to != null)
+ //set the message recipients
+ foreach (string recipient in _to)
{
- foreach (String recipient in _to)
- {
- message.AddTo(recipient);
- }
+ message.AddTo(recipient);
}
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ message.Html = "<p style='color:red';>Hello World Gravatar Email</p>";
+
+ //set the message subject
+ message.Subject = "Hello World Gravatar Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable gravatar
+ message.EnableGravatar();
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Enable the Open Tracking to track when emails are opened.
+ /// http://docs.sendgrid.com/documentation/apps/open-tracking/
+ /// </summary>
+ public void EnableOpenTrackingEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
- if(_bcc != null)
+ //set the message recipients
+ foreach (string recipient in _to)
{
- foreach (String blindcc in _bcc)
- {
- message.AddBcc(blindcc);
- }
+ message.AddTo(recipient);
}
-
- if(_cc != null)
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ message.Html = "<p style='color:red';>Hello World Plain Text</p>";
+
+ //set the message subject
+ message.Subject = "Hello World Open Tracking Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable gravatar
+ message.EnableOpenTracking();
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Point the urls to Sendgrid Servers so that the clicks can be logged before
+ /// being directed to the appropriate link
+ /// http://docs.sendgrid.com/documentation/apps/click-tracking/
+ /// </summary>
+ public void EnableClickTrackingEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
{
- foreach (String cc in _cc)
- {
- message.AddCc(cc);
- }
+ message.AddTo(recipient);
}
- var headers = new Dictionary<String, String>
- {
- {"key1", "value1"},
- {"key2", "value2"},
- {"icanhazcheeze", "kthnxbye"}
- };
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World HTML </p> <a href='http://microsoft.com'>Checkout Microsoft!!</a>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "hello world http://microsoft.com";
+
+ //set the message subject
+ message.Subject = "Hello World Click Tracking Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
- message.AddHeaders(headers);
+ //enable clicktracking
+ message.EnableClickTracking(false);
- //var replyTo = new List<MailAddress> { new MailAddress("tyler.bischel@sendgrid.com") };
+ //send the mail
+ transportInstance.Deliver(message);
+ }
- //message.ReplyTo = replyTo.ToArray();
+ /// <summary>
+ /// The Spam Checker filter, is useful when your web application allows your end users
+ /// to create content that is then emailed through your SendGrid account.
+ /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/
+ /// </summary>
+ public void EnableSpamCheckEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
//set the sender
message.From = new MailAddress(_from);
//set the message body
- message.Html = "<html><p>Hello</p><p>World</p></html>";
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>VIAGRA!!!!!! Viagra!!! CHECKOUT THIS VIAGRA!!!! MALE ENHANCEMENT!!! </p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ //set the message subject
+ message.Subject = "WIN A MILLION DOLLARS TODAY! WORK FROM HOME! A NIGERIAN PRINCE WANTS YOU!";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable spamcheck
+ message.EnableSpamCheck();
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Add automatic unsubscribe links to the bottom of emails.
+ /// http://docs.sendgrid.com/documentation/apps/subscription-tracking/
+ /// </summary>
+ public void EnableUnsubscribeEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "This is the HTML body";
+
+ message.Text = "This is the plain text body";
+
+ //set the message subject
+ message.Subject = "Hello World Unsubscribe Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable spamcheck
+ //or optionally, you can specify 'replace' instead of the text and html in order to
+ //place the link wherever you want.
+ message.EnableUnsubscribe("Please click the following link to unsubscribe: <% %>", "Please click <% here %> to unsubscribe");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
+ /// http://docs.sendgrid.com/documentation/apps/footer/
+ /// </summary>
+ public void EnableFooterEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Footer Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //Enable Footer
+ message.EnableFooter("PLAIN TEXT FOOTER", "<p color='blue'>HTML FOOTER TEXT</p>");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
+ /// http://docs.sendgrid.com/documentation/apps/google-analytics/
+ /// </summary>
+ public void EnableGoogleAnalytics()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+ message.Html += "Checkout my page at <a href=\"http://microsoft.com\">Microsoft</a>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Footer Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable Google Analytics
+ message.EnableGoogleAnalytics("SendGridTest", "EMAIL", "Sendgrid", "ad-one", "My SG Campaign");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// This feature wraps an HTML template around your email content.
+ /// This can be useful for sending out newsletters and/or other HTML formatted messages.
+ /// http://docs.sendgrid.com/documentation/apps/email-templates/
+ /// </summary>
+ public void EnableTemplateEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
//set the message subject
- message.Subject = "Hello World Simple Test";
+ message.Subject = "Hello World Template Test";
+
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable template
+ message.EnableTemplate("<p>My Email Template <% body %> is awesome!</p>");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// This feature wraps an HTML template around your email content.
+ /// This can be useful for sending out newsletters and/or other HTML formatted messages.
+ /// hhttp://docs.sendgrid.com/documentation/apps/email-templates/
+ /// </summary>
+ public void EnableBypassListManagementEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
- message.AddAttachment(@"D:\att_proj\21.jpg");
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Bypass List Management Test";
- //Utils.PrepareAttachments();
+ //create an instance of the REST transport mechanism
+ var transportInstance = REST.GetInstance(new NetworkCredential(_username, _password));
- //create an instance of the SMTP transport mechanism
- var restInstance = REST.GetInstance(new NetworkCredential(_username, _password));
+ //enable bypass list management
+ message.EnableBypassListManagement();
//send the mail
- restInstance.Deliver(message);
+ transportInstance.Deliver(message);
}
}
}
diff --git a/SendGrid/Example/SMTPAPI.cs b/SendGrid/Example/SMTPAPI.cs index b46520b..ca80f69 100755 --- a/SendGrid/Example/SMTPAPI.cs +++ b/SendGrid/Example/SMTPAPI.cs @@ -12,9 +12,9 @@ namespace Example private String _username;
private String _password;
private String _from;
- private IEnumerable<string> _to;
+ private IEnumerable<String> _to;
- public SMTPAPI(String username, String password, String from, IEnumerable<string> recipients)
+ public SMTPAPI(String username, String password, String from, IEnumerable<String> recipients)
{
_username = username;
_password = password;
@@ -28,7 +28,7 @@ namespace Example public void SimpleHTMLEmail()
{
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
foreach(string recipient in _to)
@@ -43,13 +43,13 @@ namespace Example message.Html = "<html><p>Hello</p><p>World</p></html>";
//set the message subject
- message.Subject = "Hello World Simple Test";
+ message.Subject = "Hello World HTML Test";
//create an instance of the SMTP transport mechanism
- var smtpInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
//send the mail
- smtpInstance.Deliver(message);
+ transportInstance.Deliver(message);
}
/// <summary>
@@ -58,7 +58,7 @@ namespace Example public void SimplePlaintextEmail()
{
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
foreach(string recipient in _to)
@@ -73,24 +73,24 @@ namespace Example message.Text = "Hello World Plain Text";
//set the message subject
- message.Subject = "Hello World Simple Test";
+ message.Subject = "Hello World Plain Text Test";
//create an instance of the SMTP transport mechanism
- var smtpInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
//send the mail
- smtpInstance.Deliver(message);
+ transportInstance.Deliver(message);
}
/// <summary>
/// Enable The Gravatar Filter.
- /// Currently the filter a 1x1 pixel gravatar image.
- /// Find more info at http://docs.sendgrid.com/documentation/apps/gravatar/
+ /// Currently the filter generates a 1x1 pixel gravatar image.
+ /// http://docs.sendgrid.com/documentation/apps/gravatar/
/// </summary>
public void EnableGravatarEmail()
{
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
foreach (string recipient in _to)
@@ -108,13 +108,13 @@ namespace Example message.Subject = "Hello World Gravatar Test";
//create an instance of the SMTP transport mechanism
- var smtpInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
//enable gravatar
message.EnableGravatar();
//send the mail
- smtpInstance.Deliver(message);
+ transportInstance.Deliver(message);
}
/// <summary>
@@ -123,9 +123,8 @@ namespace Example /// </summary>
public void EnableOpenTrackingEmail()
{
- var header = new Header();
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
foreach (string recipient in _to)
@@ -143,28 +142,24 @@ namespace Example message.Subject = "Hello World Open Tracking Test";
//create an instance of the SMTP transport mechanism
- var smtpInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
//enable gravatar
message.EnableOpenTracking();
- Console.WriteLine(header.AsJson());
-
//send the mail
- smtpInstance.Deliver(message);
-
- Console.WriteLine("done");
+ transportInstance.Deliver(message);
}
/// <summary>
- /// Enable the Open Tracking to track when emails are opened.
- /// http://docs.sendgrid.com/documentation/apps/open-tracking/
+ /// Point the urls to Sendgrid Servers so that the clicks can be logged before
+ /// being directed to the appropriate link
+ /// http://docs.sendgrid.com/documentation/apps/click-tracking/
/// </summary>
public void EnableClickTrackingEmail()
{
- var header = new Header();
//create a new message object
- var message = SendGrid.GenerateInstance();
+ var message = SendGrid.GetInstance();
//set the message recipients
foreach (string recipient in _to)
@@ -177,25 +172,253 @@ namespace Example //set the message body
var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World Plain Text</p> <a href = 'http://microsoft.com'>Checkout Microsoft!!</a>";
+ message.Html = "<p style='color:red';>Hello World HTML </p> <a href='http://microsoft.com'>Checkout Microsoft!!</a>";
message.Html += "<p>Sent At : " + timestamp + "</p>";
+ message.Text = "hello world http://microsoft.com";
+
//set the message subject
message.Subject = "Hello World Click Tracking Test";
//create an instance of the SMTP transport mechanism
- var smtpInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password));
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
//enable clicktracking
- message.EnableClickTracking("1");
+ message.EnableClickTracking(false);
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// The Spam Checker filter, is useful when your web application allows your end users
+ /// to create content that is then emailed through your SendGrid account.
+ /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/
+ /// </summary>
+ public void EnableSpamCheckEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>VIAGRA!!!!!! Viagra!!! CHECKOUT THIS VIAGRA!!!! MALE ENHANCEMENT!!! </p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ //set the message subject
+ message.Subject = "WIN A MILLION DOLLARS TODAY! WORK FROM HOME! A NIGERIAN PRINCE WANTS YOU!";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable spamcheck
+ message.EnableSpamCheck();
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// Add automatic unsubscribe links to the bottom of emails.
+ /// http://docs.sendgrid.com/documentation/apps/subscription-tracking/
+ /// </summary>
+ public void EnableUnsubscribeEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
- Console.WriteLine(header.AsJson());
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "This is the HTML body";
+
+ message.Text = "This is the plain text body";
+
+ //set the message subject
+ message.Subject = "Hello World Unsubscribe Test";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable spamcheck
+ //or optionally, you can specify 'replace' instead of the text and html in order to
+ //place the link wherever you want.
+ message.EnableUnsubscribe("Please click the following link to unsubscribe: <% %>", "Please click <% here %> to unsubscribe");
//send the mail
- smtpInstance.Deliver(message);
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
+ /// http://docs.sendgrid.com/documentation/apps/footer/
+ /// </summary>
+ public void EnableFooterEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
- Console.WriteLine("done");
- Console.WriteLine("Sent at : "+timestamp);
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Footer Test";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //Enable Footer
+ message.EnableFooter("PLAIN TEXT FOOTER", "<p color='blue'>HTML FOOTER TEXT</p>");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
+ /// http://docs.sendgrid.com/documentation/apps/google-analytics/
+ /// </summary>
+ public void EnableGoogleAnalytics()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+ message.Html += "Checkout my page at <a href=\"http://microsoft.com\">Microsoft</a>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Footer Test";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable Google Analytics
+ message.EnableGoogleAnalytics("SendGridTest", "EMAIL", "Sendgrid", "ad-one", "My SG Campaign");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// This feature wraps an HTML template around your email content.
+ /// This can be useful for sending out newsletters and/or other HTML formatted messages.
+ /// http://docs.sendgrid.com/documentation/apps/email-templates/
+ /// </summary>
+ public void EnableTemplateEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Template Test";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable template
+ message.EnableTemplate("<p>My Email Template <% body %> is awesome!</p>");
+
+ //send the mail
+ transportInstance.Deliver(message);
+ }
+
+ /// <summary>
+ /// This feature wraps an HTML template around your email content.
+ /// This can be useful for sending out newsletters and/or other HTML formatted messages.
+ /// hhttp://docs.sendgrid.com/documentation/apps/email-templates/
+ /// </summary>
+ public void EnableBypassListManagementEmail()
+ {
+ //create a new message object
+ var message = SendGrid.GetInstance();
+
+ //set the message recipients
+ foreach (string recipient in _to)
+ {
+ message.AddTo(recipient);
+ }
+
+ //set the sender
+ message.From = new MailAddress(_from);
+
+ //set the message body
+ var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
+ message.Html = "<p style='color:red';>Hello World</p>";
+ message.Html += "<p>Sent At : " + timestamp + "</p>";
+
+ message.Text = "Hello World plain text";
+
+ //set the message subject
+ message.Subject = "Hello World Bypass List Management Test";
+
+ //create an instance of the SMTP transport mechanism
+ var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password));
+
+ //enable bypass list management
+ message.EnableBypassListManagement();
+
+ //send the mail
+ transportInstance.Deliver(message);
}
}
diff --git a/SendGrid/SendGridMail/ISendGrid.cs b/SendGrid/SendGridMail/ISendGrid.cs index a292edc..08d109c 100755 --- a/SendGrid/SendGridMail/ISendGrid.cs +++ b/SendGrid/SendGridMail/ISendGrid.cs @@ -1,11 +1,7 @@ using System;
using System.Collections.Generic;
-using System.IO;
-using System.Linq;
using System.Net;
using System.Net.Mail;
-using System.Net.Mime;
-using System.Text;
namespace SendGridMail
{
@@ -41,84 +37,90 @@ namespace SendGridMail #endregion
#region Interface for ITransport
+ /// <summary>
+ /// Used by the Transport object to create a MIME for SMTP
+ /// </summary>
+ /// <returns>MIME to be sent</returns>
MailMessage CreateMimeMessage();
+
+ /// <summary>
+ /// Creates a new transport object, and sends this message out.
+ /// </summary>
+ /// <param name="credentials">Sendgrid user credentials</param>
+ void Mail(NetworkCredential credentials);
+
#endregion
#region Methods for setting data
/// <summary>
- /// Set the To address. In this case the input is a single string eg. 'you@company.com'
+ /// Add to the 'To' address.
/// </summary>
- /// <param name="address"></param>
+ /// <param name="address">single string eg. 'you@company.com'</param>
void AddTo(String address);
+
/// <summary>
- /// Set the To address. In this case the expected input is a list of addresses as strings
+ /// Add to the 'To' address.
/// </summary>
- /// <param name="addresses"></param>
+ /// <param name="addresses">list of email addresses as strings</param>
void AddTo(IEnumerable<String> addresses);
+
/// <summary>
- /// Set the To address. In this case the expected input is a list of addresses with paramaters.
- /// The first parameter is a string for the email address.
- /// The second paramater is a dictionary containing the key, value pairs for a property's name and its value.
- /// Currently the only value that you can set with the MailAddress data object is the 'DisplayName' field.
+ /// Add to the 'To' address.
/// </summary>
- /// <param name="addresssInfo"></param>
+ /// <param name="addresssInfo"> the dictionary keys are the email addresses, which points to a dictionary of
+ /// key value pairs mapping to other address codes, such as { foo@bar.com => { 'DisplayName' => 'Mr Foo' } } </param>
void AddTo(IDictionary<String, IDictionary<String, String>> addresssInfo);
/// <summary>
- /// Add the CC address. In this case the expected input is a single email address eg "you@company.com"
+ /// Add to the 'CC' address.
/// </summary>
- /// <param name="address"></param>
+ /// <param name="address">a single email address eg "you@company.com"</param>
void AddCc(String address);
+
/// <summary>
- /// Set the CC address. In this case the expected input is a list of addresses as strings
+ /// Add to the 'CC' address.
/// </summary>
- /// <param name="addresses"></param>
+ /// <param name="addresses">a list of email addresses as strings</param>
void AddCc(IEnumerable<String> addresses);
+
/// <summary>
- /// Set the CC address. In this case the expected input is a list of addresses with paramaters.
- /// The first parameter is a string for the email address.
- /// The second paramater is a dictionary containing the key, value pairs for a property's name and its value.
- /// Currently the only value that you can set with the MailAddress data object is the 'DisplayName' field.
+ /// Add to the 'CC' address.
/// </summary>
- /// <param name="addresssInfo"></param>
+ /// <param name="addresssInfo">the dictionary keys are the email addresses, which points to a dictionary of
+ /// key value pairs mapping to other address codes, such as { foo@bar.com => { 'DisplayName' => 'Mr Foo' } } </param>
void AddCc(IDictionary<String, IDictionary<String, String>> addresssInfo);
/// <summary>
- /// Set the Bcc address. Expects a single email as the input eg "you@company.com"
+ /// Add to the 'Bcc' address.
/// </summary>
- /// <param name="address"></param>
+ /// <param name="address">a single email as the input eg "you@company.com"</param>
void AddBcc(String address);
+
/// <summary>
- /// Set the Bcc address. Expects a list of emails as an array of strings.
+ /// Add to the 'Bcc' address.
/// </summary>
- /// <param name="addresses"></param>
+ /// <param name="addresses">a list of emails as an array of strings.</param>
void AddBcc(IEnumerable<String> addresses);
+
/// <summary>
- /// Set the Bcc address. In this case the expected input is a list of addresses with paramaters.
- /// The first parameter is a string for the email address.
- /// The second paramater is a dictionary containing the key, value pairs for a property's name and its value.
- /// Currently the only value that you can set with the MailAddress data object is the 'DisplayName' field.
+ /// Add to the 'Bcc' address.
/// </summary>
- /// <param name="addresssInfo"></param>
+ /// <param name="addresssInfo">the dictionary keys are the email addresses, which points to a dictionary of
+ /// key value pairs mapping to other address codes, such as { foo@bar.com => { 'DisplayName' => 'Mr Foo' } }</param>
void AddBcc(IDictionary<String, IDictionary<String, String>> addresssInfo);
/// <summary>
- /// Sets a list of substitution values for the email.
- /// the 'tag' parameter is the value in the email that you'll replace eg. '-name-'
- /// the 'value' parameter is a list of values that will be substituted in for the tag.
- /// In our example above the list would be something like ['eric', 'tyler', 'cj'].
- /// The 'value' parameter expects a 1:1 mapping from email addresses to values.
- /// If you are left with more email addresses then values to substitute then the substitution tag will be left blank.
+ /// Adds a substitution value to be used during the mail merge. Substitutions will happen in the order
+ /// added, so calls to this should match calls to addTo.
/// </summary>
- /// <param name="tag"></param>
- /// <param name="value"></param>
+ /// <param name="tag">the string in the email that you'll replace eg. '-name-'</param>
+ /// <param name="value">a list of values that will be substituted in for the tag, one for each recipient</param>
void AddSubVal(String tag, params String[] value);
/// <summary>
- /// Add an attachment to the message.
- /// The 'filePath' paramater expects a fully qualified file path as a string
+ /// Add an attachment to the message.
/// </summary>
- /// <param name="filePath"></param>
+ /// <param name="filePath">a fully qualified file path as a string</param>
void AddAttachment(String filePath);
/// <summary>
@@ -135,29 +137,127 @@ namespace SendGridMail #endregion
#region SMTP API Functions
+ /// <summary>
+ /// Disable the gravatar app
+ /// </summary>
void DisableGravatar();
+
+ /// <summary>
+ /// Disable the open tracking app
+ /// </summary>
void DisableOpenTracking();
+
+ /// <summary>
+ /// Disable the click tracking app
+ /// </summary>
void DisableClickTracking();
+
+ /// <summary>
+ /// Disable the spam check
+ /// </summary>
void DisableSpamCheck();
+
+ /// <summary>
+ /// Disable the unsubscribe app
+ /// </summary>
void DisableUnsubscribe();
+
+ /// <summary>
+ /// Disable the footer app
+ /// </summary>
void DisableFooter();
+
+ /// <summary>
+ /// Disable the Google Analytics app
+ /// </summary>
void DisableGoogleAnalytics();
+
+ /// <summary>
+ /// Disable the templates app
+ /// </summary>
void DisableTemplate();
+
+ /// <summary>
+ /// Disable Bcc app
+ /// </summary>
void DisableBcc();
+
+ /// <summary>
+ /// Disable the Bypass List Management app
+ /// </summary>
void DisableBypassListManagement();
+ /// <summary>
+ /// Inserts the gravatar image of the sender to the bottom of the message
+ /// </summary>
void EnableGravatar();
+
+ /// <summary>
+ /// Adds an invisible image to the end of the email which can track e-mail opens.
+ /// </summary>
void EnableOpenTracking();
- void EnableClickTracking(String text = null);
+
+ /// <summary>
+ /// Causes all links to be overwritten, shortened, and pointed to SendGrid's servers so clicks will be tracked.
+ /// </summary>
+ /// <param name="includePlainText">true if links found in plain text portions of the message are to be overwritten</param>
+ void EnableClickTracking(bool includePlainText = false);
+
+ /// <summary>
+ /// Provides notification when emails are deteched that exceed a predefined spam threshold.
+ /// </summary>
+ /// <param name="score">Emails with a SpamAssassin score over this value will be considered spam and not be delivered.</param>
+ /// <param name="url">SendGrid will send an HTTP POST request to this url when a message is detected as spam</param>
void EnableSpamCheck(int score = 5, String url = null);
- void EnableUnsubscribe(String text, String html, String replace, String url, String landing);
+
+ /// <summary>
+ /// Allow's SendGrid to manage unsubscribes and ensure these users don't get future emails from the sender
+ /// </summary>
+ /// <param name="text">String for the plain text email body showing what you want the message to look like.</param>
+ /// <param name="html">String for the HTML email body showing what you want the message to look like.</param>
+ void EnableUnsubscribe(String text, String html);
+
+ /// <summary>
+ /// Allow's SendGrid to manage unsubscribes and ensure these users don't get future emails from the sender
+ /// </summary>
+ /// <param name="replace">Tag in the message body to be replaced with the unsubscribe link and message</param>
+ void EnableUnsubscribe(String replace);
+
+ /// <summary>
+ /// Attaches a message at the footer of the email
+ /// </summary>
+ /// <param name="text">Message for the plain text body of the email</param>
+ /// <param name="html">Message for the HTML body of the email</param>
void EnableFooter(String text = null, String html = null);
+
+ /// <summary>
+ /// Re-writes links to integrate with Google Analytics
+ /// </summary>
+ /// <param name="source">Name of the referrer source (e.g. Google, SomeDomain.com, NewsletterA)</param>
+ /// <param name="medium">Name of the marketing medium (e.g. Email)</param>
+ /// <param name="term">Identify paid keywords</param>
+ /// <param name="content">Use to differentiate ads</param>
+ /// <param name="campaign">Name of the campaign</param>
void EnableGoogleAnalytics(String source, String medium, String term, String content = null, String campaign = null);
+
+ /// <summary>
+ /// Wraps an HTML template around your email content.
+ /// </summary>
+ /// <param name="html">HTML that your emails will be wrapped in, containing a body tag.</param>
void EnableTemplate(String html = null);
+
+ /// <summary>
+ /// Automatically sends a blind carbon copy to an address for every e-mail sent, without
+ /// adding that address to the header.
+ /// </summary>
+ /// <param name="email">A single email recipient</param>
void EnableBcc(String email = null);
+
+ /// <summary>
+ /// Enabing this app will bypass the normal unsubscribe / bounce / spam report checks
+ /// and queue the e-mail for delivery.
+ /// </summary>
void EnableBypassListManagement();
#endregion
-
- void Mail(NetworkCredential credentials);
}
}
diff --git a/SendGrid/SendGridMail/Mail.csproj b/SendGrid/SendGridMail/Mail.csproj index f333f36..bd1dc7a 100755 --- a/SendGrid/SendGridMail/Mail.csproj +++ b/SendGrid/SendGridMail/Mail.csproj @@ -31,8 +31,9 @@ <WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
- <Reference Include="CodeScales.Http">
- <HintPath>..\packages\CodeScales.Http.dll</HintPath>
+ <Reference Include="CodeScales.Http, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>lib\CodeScales.Http.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
@@ -56,7 +57,9 @@ <Compile Include="Transport\REST.cs" />
<Compile Include="Transport\SMTP.cs" />
<Compile Include="Utils.cs" />
- <Compile Include="WebFileUpload.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="lib\CodeScales.Http.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
diff --git a/SendGrid/SendGridMail/Mail.nuspec b/SendGrid/SendGridMail/Mail.nuspec new file mode 100755 index 0000000..39d44bf --- /dev/null +++ b/SendGrid/SendGridMail/Mail.nuspec @@ -0,0 +1,15 @@ +<?xml version="1.0"?>
+<package >
+ <metadata>
+ <id>Sendgrid</id>
+ <version>1.0.0</version>
+ <title>Sendgrid</title>
+ <authors>CJ Buchmann, Tyler Bischel, Eric Becking</authors>
+ <owners>Sendgrid</owners>
+ <requireLicenseAcceptance>false</requireLicenseAcceptance>
+ <description>$description$</description>
+ <releaseNotes>Basic C# client library and examples for using Sendgrid API's to send mail</releaseNotes>
+ <copyright>Copyright 2012</copyright>
+ <tags>Sendgrid Email Mail Microsoft Azure</tags>
+ </metadata>
+</package>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Properties/AssemblyInfo.cs b/SendGrid/SendGridMail/Properties/AssemblyInfo.cs index 0108aa9..e6e890f 100755 --- a/SendGrid/SendGridMail/Properties/AssemblyInfo.cs +++ b/SendGrid/SendGridMail/Properties/AssemblyInfo.cs @@ -6,9 +6,9 @@ using System.Runtime.InteropServices; // set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SendGridMail")]
-[assembly: AssemblyDescription("")]
+[assembly: AssemblyDescription("A client library for interfacing with the SendGrid API")]
[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
+[assembly: AssemblyCompany("SendGrid")]
[assembly: AssemblyProduct("SendGridMail")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
diff --git a/SendGrid/SendGridMail/SendGrid.cs b/SendGrid/SendGridMail/SendGrid.cs index 0a6a466..59d7976 100755 --- a/SendGrid/SendGridMail/SendGrid.cs +++ b/SendGrid/SendGridMail/SendGrid.cs @@ -1,13 +1,10 @@ using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
-using System.Runtime.InteropServices.ComTypes;
-using System.Text;
using SendGridMail.Transport;
namespace SendGridMail
@@ -33,7 +30,7 @@ namespace SendGridMail /// Creates an instance of SendGrid's custom message object
/// </summary>
/// <returns></returns>
- public static SendGrid GenerateInstance()
+ public static SendGrid GetInstance()
{
var header = new Header();
return new SendGrid(header);
@@ -51,7 +48,7 @@ namespace SendGridMail /// <param name="text">the plain text part of the message</param>
/// <param name="transport">Transport class to use for sending the message</param>
/// <returns></returns>
- public static SendGrid GenerateInstance(MailAddress from, MailAddress[] to, MailAddress[] cc, MailAddress[] bcc,
+ public static SendGrid GetInstance(MailAddress from, MailAddress[] to, MailAddress[] cc, MailAddress[] bcc,
String subject, String html, String text, TransportType transport)
{
var header = new Header();
@@ -319,151 +316,156 @@ namespace SendGridMail #region SMTP API Functions
public void DisableGravatar()
{
- Header.Disable(this._filters["Gravatar"]);
+ Header.Disable(_filters["Gravatar"]);
}
public void DisableOpenTracking()
{
- Header.Disable(this._filters["OpenTracking"]);
+ Header.Disable(_filters["OpenTracking"]);
}
public void DisableClickTracking()
{
- Header.Disable(this._filters["ClickTracking"]);
+ Header.Disable(_filters["ClickTracking"]);
}
public void DisableSpamCheck()
{
- Header.Disable(this._filters["SpamCheck"]);
+ Header.Disable(_filters["SpamCheck"]);
}
public void DisableUnsubscribe()
{
- Header.Disable(this._filters["Unsubscribe"]);
+ Header.Disable(_filters["Unsubscribe"]);
}
public void DisableFooter()
{
- Header.Disable(this._filters["Footer"]);
+ Header.Disable(_filters["Footer"]);
}
public void DisableGoogleAnalytics()
{
- Header.Disable(this._filters["GoogleAnalytics"]);
+ Header.Disable(_filters["GoogleAnalytics"]);
}
public void DisableTemplate()
{
- Header.Disable(this._filters["Template"]);
+ Header.Disable(_filters["Template"]);
}
public void DisableBcc()
{
- Header.Disable(this._filters["Bcc"]);
+ Header.Disable(_filters["Bcc"]);
}
public void DisableBypassListManagement()
{
- Header.Disable(this._filters["BypassListManagement"]);
+ Header.Disable(_filters["BypassListManagement"]);
}
public void EnableGravatar()
{
- Header.Enable(this._filters["Gravatar"]);
+ Header.Enable(_filters["Gravatar"]);
}
public void EnableOpenTracking()
{
- Header.Enable(this._filters["OpenTracking"]);
+ Header.Enable(_filters["OpenTracking"]);
}
- public void EnableClickTracking(String enableText = null)
+ public void EnableClickTracking(bool includePlainText = false)
{
- var filter = this._filters["ClickTracking"];
+ var filter = _filters["ClickTracking"];
Header.Enable(filter);
- if (enableText != null)
+ if (includePlainText)
{
- Header.AddFilterSetting(filter, new List<string>() { "enable" }, enableText);
+ Header.AddFilterSetting(filter, new List<string> { "enable_text" }, "1");
}
}
public void EnableSpamCheck(int score = 5, string url = null)
{
- var filter = this._filters["SpamCheck"];
+ var filter = _filters["SpamCheck"];
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "score" }, score.ToString(CultureInfo.InvariantCulture));
- Header.AddFilterSetting(filter, new List<string>(){ "url" }, url);
+ Header.AddFilterSetting(filter, new List<string> { "maxscore" }, score.ToString(CultureInfo.InvariantCulture));
+ Header.AddFilterSetting(filter, new List<string> { "url" }, url);
}
- public void EnableUnsubscribe(string text, string html, string replace, string url, string landing)
+ public void EnableUnsubscribe(string text, string html)
{
- var filter = this._filters["Unsubscribe"];
+ var filter = _filters["Unsubscribe"];
- if(!System.Text.RegularExpressions.Regex.IsMatch(text, SendGrid.ReText))
+ if(!System.Text.RegularExpressions.Regex.IsMatch(text, ReText))
{
throw new Exception("Missing substitution tag in text");
}
- if(!System.Text.RegularExpressions.Regex.IsMatch(html, SendGrid.ReHtml))
+ if(!System.Text.RegularExpressions.Regex.IsMatch(html, ReHtml))
{
throw new Exception("Missing substitution tag in html");
}
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "text" }, text);
- Header.AddFilterSetting(filter, new List<string>(){ "html" }, html);
- Header.AddFilterSetting(filter, new List<string>(){ "replace"}, replace);
- Header.AddFilterSetting(filter, new List<string>(){ "url"}, url);
- Header.AddFilterSetting(filter, new List<string>(){ "landing" }, landing);
+ Header.AddFilterSetting(filter, new List<string> { "text/plain" }, text);
+ Header.AddFilterSetting(filter, new List<string> {"text/html"}, html);
+ }
+
+ public void EnableUnsubscribe(string replace)
+ {
+ var filter = _filters["Unsubscribe"];
+
+ Header.Enable(filter);
+ Header.AddFilterSetting(filter, new List<string> { "replace" }, replace);
}
public void EnableFooter(string text = null, string html = null)
{
- var filter = this._filters["Footer"];
+ var filter = _filters["Footer"];
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "text" }, text);
- Header.AddFilterSetting(filter, new List<string>(){ "html" }, html);
+ Header.AddFilterSetting(filter, new List<string> { "text/plain" }, text);
+ Header.AddFilterSetting(filter, new List<string> { "text/html" }, html);
}
public void EnableGoogleAnalytics(string source, string medium, string term, string content = null, string campaign = null)
{
- var filter = this._filters["GoogleAnalytics"];
+ var filter = _filters["GoogleAnalytics"];
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "source" }, source);
- Header.AddFilterSetting(filter, new List<string>(){ "medium" }, medium);
- Header.AddFilterSetting(filter, new List<string>(){ "term" }, term);
- Header.AddFilterSetting(filter, new List<string>(){ "content" }, content);
- Header.AddFilterSetting(filter, new List<string>(){ "campaign" }, campaign);
+ Header.AddFilterSetting(filter, new List<string> { "utm_source" }, source);
+ Header.AddFilterSetting(filter, new List<string> { "utm_medium" }, medium);
+ Header.AddFilterSetting(filter, new List<string> { "utm_term" }, term);
+ Header.AddFilterSetting(filter, new List<string> { "utm_content" }, content);
+ Header.AddFilterSetting(filter, new List<string> { "utm_campaign" }, campaign);
}
public void EnableTemplate(string html)
{
- var filter = this._filters["Template"];
+ var filter = _filters["Template"];
- if (!System.Text.RegularExpressions.Regex.IsMatch(html, SendGrid.ReHtml))
+ if (!System.Text.RegularExpressions.Regex.IsMatch(html, ReHtml))
{
throw new Exception("Missing substitution tag in html");
}
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "html" }, html);
+ Header.AddFilterSetting(filter, new List<string> { "text/html" }, html);
}
public void EnableBcc(string email)
{
- var filter = this._filters["Bcc"];
+ var filter = _filters["Bcc"];
Header.Enable(filter);
- Header.AddFilterSetting(filter, new List<string>(){ "email" }, email);
+ Header.AddFilterSetting(filter, new List<string> { "email" }, email);
}
public void EnableBypassListManagement()
{
- Header.Enable(this._filters["BypassListManagement"]);
+ Header.Enable(_filters["BypassListManagement"]);
}
#endregion
@@ -509,7 +511,7 @@ namespace SendGridMail /// Helper function lets us look at the mime before it is sent
/// </summary>
/// <param name="directory">directory in which we store this mime message</param>
- internal void SaveMessage(String directory)
+ public void SaveMessage(String directory)
{
var client = new SmtpClient("localhost")
{
@@ -526,7 +528,7 @@ namespace SendGridMail switch (Transport)
{
case TransportType.SMTP:
- transport = SMTP.GenerateInstance(credentials);
+ transport = SMTP.GetInstance(credentials);
break;
case TransportType.REST:
transport = REST.GetInstance(credentials);
diff --git a/SendGrid/SendGridMail/Sendgrid.1.0.0.nupkg b/SendGrid/SendGridMail/Sendgrid.1.0.0.nupkg Binary files differnew file mode 100755 index 0000000..aeaf84e --- /dev/null +++ b/SendGrid/SendGridMail/Sendgrid.1.0.0.nupkg diff --git a/SendGrid/SendGridMail/Transport/ITransport.cs b/SendGrid/SendGridMail/Transport/ITransport.cs index 26fccf4..b3a1936 100755 --- a/SendGrid/SendGridMail/Transport/ITransport.cs +++ b/SendGrid/SendGridMail/Transport/ITransport.cs @@ -1,7 +1,8 @@ namespace SendGridMail.Transport
{
/// <summary>
- ///
+ /// Encapsulates the transport mechanism so that it can be used in a generic way,
+ /// regardless of the transport type
/// </summary>
public interface ITransport
{
@@ -11,4 +12,4 @@ /// <param name="message">the message to be delivered</param>
void Deliver(ISendGrid message);
}
-}
+}
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Transport/REST.cs b/SendGrid/SendGridMail/Transport/REST.cs index f96fa21..614e024 100755 --- a/SendGrid/SendGridMail/Transport/REST.cs +++ b/SendGrid/SendGridMail/Transport/REST.cs @@ -1,41 +1,45 @@ using System;
using System.Collections.Generic;
-using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
-using System.Net.Mail;
using System.Text;
-using System.Web;
using System.Xml;
using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Entity.Mime;
using CodeScales.Http.Methods;
-using HttpResponse = System.Web.HttpResponse;
namespace SendGridMail.Transport
{
public class REST : ITransport
{
- // REST delivery settings
+ #region Properties
public const String Endpoint = "http://sendgrid.com/api/mail.send";
public const String JsonFormat = "json";
public const String XmlFormat = "xml";
- private readonly List<KeyValuePair<String, String>> _query;
private readonly NetworkCredential _credentials;
- private readonly NameValueCollection _queryParameters;
private readonly String _restEndpoint;
private readonly String _format;
-
- private WebFileUpload _fileUpload;
-
+ #endregion
+
+ /// <summary>
+ /// Factory method for REST transport of sendgrid messages
+ /// </summary>
+ /// <param name="credentials">SendGrid credentials for sending mail messages</param>
+ /// <param name="url">The uri of the REST endpoint</param>
+ /// <returns>New instance of the transport mechanism</returns>
public static REST GetInstance(NetworkCredential credentials, String url = Endpoint)
{
return new REST(credentials, url);
}
+ /// <summary>
+ /// Creates a new REST interface for sending mail. Preference is using the Factory method.
+ /// </summary>
+ /// <param name="credentials">SendGrid user parameters</param>
+ /// <param name="url">The uri of the REST endpoint</param>
internal REST(NetworkCredential credentials, String url = Endpoint)
{
_credentials = credentials;
@@ -44,7 +48,74 @@ namespace SendGridMail.Transport _restEndpoint = url + "." + _format;
}
- private List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
+ /// <summary>
+ /// Delivers a message over SendGrid's REST interface
+ /// </summary>
+ /// <param name="message"></param>
+ public void Deliver(ISendGrid message)
+ {
+ MultipartEntity multipartEntity;
+ HttpPost postMethod;
+
+ var client = InitializeTransport(out multipartEntity, out postMethod);
+ AttachFormParams(message, multipartEntity);
+ AttachFiles(message, multipartEntity);
+ var response = client.Execute(postMethod);
+ CheckForErrors(response);
+ }
+
+ #region Support Methods
+
+ internal HttpClient InitializeTransport(out MultipartEntity multipartEntity, out HttpPost postMethod)
+ {
+ var client = new HttpClient();
+ postMethod = new HttpPost(new Uri(_restEndpoint));
+
+ multipartEntity = new MultipartEntity();
+ postMethod.Entity = multipartEntity;
+ return client;
+ }
+
+ private void AttachFormParams(ISendGrid message, MultipartEntity multipartEntity)
+ {
+ var formParams = FetchFormParams(message);
+ formParams.ForEach(kvp => multipartEntity.AddBody(new StringBody(Encoding.UTF8, kvp.Key, kvp.Value)));
+ }
+
+ private void AttachFiles(ISendGrid message, MultipartEntity multipartEntity)
+ {
+ var files = FetchFileBodies(message);
+ files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files[" + kvp.Key + "]", kvp.Key, kvp.Value)));
+ }
+
+ private void CheckForErrors(CodeScales.Http.Methods.HttpResponse response)
+ {
+ var status = EntityUtils.ToString(response.Entity);
+ var stream = new MemoryStream(Encoding.UTF8.GetBytes(status));
+
+ using (var reader = XmlReader.Create(stream))
+ {
+ while (reader.Read())
+ {
+ if (reader.IsStartElement())
+ {
+ switch (reader.Name)
+ {
+ case "result":
+ break;
+ case "message": // success
+ return;
+ case "error": // failure
+ throw new ProtocolViolationException(status);
+ default:
+ throw new ArgumentException("Unknown element: " + reader.Name);
+ }
+ }
+ }
+ }
+ }
+
+ internal List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
{
var result = new List<KeyValuePair<string, string>>()
{
@@ -78,59 +149,13 @@ namespace SendGridMail.Transport return result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList();
}
- private List<KeyValuePair<String, FileInfo>> FetchFileBodies(ISendGrid message)
+ internal List<KeyValuePair<String, FileInfo>> FetchFileBodies(ISendGrid message)
{
if(message.Attachments == null)
return new List<KeyValuePair<string, FileInfo>>();
return message.Attachments.Select(name => new KeyValuePair<String, FileInfo>(name, new FileInfo(name))).ToList();
}
- public void Deliver(ISendGrid message)
- {
- var client = new HttpClient();
- var postMethod = new HttpPost(new Uri(_restEndpoint));
-
- var multipartEntity = new MultipartEntity();
- postMethod.Entity = multipartEntity;
-
- var formParams = FetchFormParams(message);
-
- formParams.ForEach(kvp => multipartEntity.AddBody(new StringBody(Encoding.UTF8, kvp.Key, kvp.Value)));
-
- var files = FetchFileBodies(message);
- files.ForEach(kvp => multipartEntity.AddBody(new FileBody("files["+kvp.Key+"]", kvp.Key, kvp.Value)));
-
- CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod);
-
- Console.WriteLine("Response Code: " + response.ResponseCode);
- Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));
-
- Console.WriteLine("Res");
-
- var status = EntityUtils.ToString(response.Entity);
- var stream = new MemoryStream(Encoding.UTF8.GetBytes(status));
-
-
- using (var reader = XmlReader.Create(stream))
- {
- while (reader.Read())
- {
- if (reader.IsStartElement())
- {
- switch (reader.Name)
- {
- case "result":
- break;
- case "message": // success
- return;
- case "error": // failure
- throw new ProtocolViolationException(status);
- default:
- throw new ArgumentException("Unknown element: " + reader.Name);
- }
- }
- }
- }
- }
+ #endregion
}
}
diff --git a/SendGrid/SendGridMail/Transport/SMTP.cs b/SendGrid/SendGridMail/Transport/SMTP.cs index 606afcd..a878ce8 100755 --- a/SendGrid/SendGridMail/Transport/SMTP.cs +++ b/SendGrid/SendGridMail/Transport/SMTP.cs @@ -72,7 +72,7 @@ namespace SendGridMail.Transport /// <param name="credentials">Sendgrid user credentials</param>
/// <param name="host">MTA recieving this message. By default, sent through SendGrid.</param>
/// <param name="port">SMTP port 25 is the default. Port 465 can be used for Secure SMTP.</param>
- public static SMTP GenerateInstance(NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
+ public static SMTP GetInstance(NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
{
var client = new SmtpWrapper(host, port, credentials, SmtpDeliveryMethod.Network);
return new SMTP(client, credentials, host, port);
@@ -86,7 +86,7 @@ namespace SendGridMail.Transport /// <param name="host"></param>
/// <param name="port"></param>
/// <returns></returns>
- internal static SMTP GenerateInstance(ISmtpClient client, NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
+ internal static SMTP GetInstance(ISmtpClient client, NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
{
return new SMTP(client, credentials, host, port);
}
diff --git a/SendGrid/SendGridMail/Utils.cs b/SendGrid/SendGridMail/Utils.cs index cb6413c..31fe92f 100755 --- a/SendGrid/SendGridMail/Utils.cs +++ b/SendGrid/SendGridMail/Utils.cs @@ -28,25 +28,5 @@ namespace SendGridMail return "{"+String.Join(",",dic.Select(kvp => Serialize(kvp.Key) + ":" + Serialize(kvp.Value)))+"}";
}
- public static Dictionary<String, Stream> PrepareAttachments()
- {
- var attach = new Attachment("D:/att_proj/21.jpg");
- Console.WriteLine("preparing message attachment");
- var sr = new StreamReader(attach.ContentStream);
-
- Console.WriteLine(sr.ReadToEnd());
-
- Console.WriteLine(":D");
- var request = (HttpWebRequest)WebRequest.Create("");
-
-
- //attach.ContentStream.CopyTo(request.GetRequestStream());
-
- Console.WriteLine("attachment: ");
-
- Console.WriteLine("DONE");
-
- return new Dictionary<string, Stream>();
- }
}
}
diff --git a/SendGrid/SendGridMail/WebFileUpload.cs b/SendGrid/SendGridMail/WebFileUpload.cs deleted file mode 100755 index b6e0faf..0000000 --- a/SendGrid/SendGridMail/WebFileUpload.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.IO;
-using System.IO.Pipes;
-using System.Linq;
-using System.Net;
-using System.Net.Mail;
-using System.Text;
-using CodeScales.Http;
-using CodeScales.Http.Common;
-using CodeScales.Http.Entity;
-using CodeScales.Http.Entity.Mime;
-using CodeScales.Http.Methods;
-
-namespace SendGridMail
-{
- internal class WebFileUpload
- {
- private HttpWebRequest _request;
- private List<Attachment> _attachments;
-
- private String newline = "\r\n";
-
- private byte[] _boundaryBytes;
-
- private String _boundary;
-
- public WebFileUpload(HttpWebRequest request)
- {
-
- }
-
- public void SendAttachments()
- {
- HttpClient client = new HttpClient();
- //https://sendgrid.com/api/mail.send
- var url = "http://sendgrid.com/api/mail.send.xml";
- var notUrl = "http://www.postbin.org/1hv8rbe";
- HttpPost postMethod = new HttpPost(new Uri(url));
-
-
-
- //UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Encoding.UTF8);
- //postMethod.Entity = formEntity;
-
-
-
- MultipartEntity multipartEntity = new MultipartEntity();
- postMethod.Entity = multipartEntity;
-
-
-
- FileInfo fileInfo = new FileInfo(@"D:\att_proj\2.JPG");
- FileBody fileBody = new FileBody("files[file1.jpg]", "myfile.jpg", fileInfo);
-
- multipartEntity.AddBody(fileBody);
-
- HttpResponse response = client.Execute(postMethod);
-
- Console.WriteLine("Response Code: " + response.ResponseCode);
- Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));
-
- Console.WriteLine("done");
- }
-
- /*public void TestAddAttachment(Attachment attachment)
- {
- WebClient myWebClient = new WebClient();
- NameValueCollection collection = new NameValueCollection();
-
- StreamReader sr = new StreamReader(attachment.ContentStream);
- var data = sr.ReadToEnd();
- byte[] bytes = new byte[attachment.ContentStream.Length];
-
- byte[] responseArray = myWebClient.UploadValues("https://sendgrid.com/api/mail.send.xml", collection);
- Console.WriteLine("\nResponse received was :\n{0}", Encoding.ASCII.GetString(responseArray));
- }*/
-
- public void AddAttachment(String filename)
- {
- _attachments.Add(new Attachment(filename));
- }
-
- public void AddAttachments(List<Attachment> attachments)
- {
- _attachments = attachments;
- }
-
- public List<Attachment> GetAttachments()
- {
- return _attachments;
- }
-
- /*public void SendAttachments()
- {
- WebResponse _response = null;
-
- try
- {
- _response = _request.GetResponse();
-
- //Stream stream = _response.GetResponseStream();
- //StreamReader reader = new StreamReader(stream);
- }
- catch (Exception ex)
- {
- throw new Exception("Unable to send attachments :: " + ex.Message);
- }
-
- _response.Close();
- }*/
- }
-}
diff --git a/SendGrid/packages/CodeScales.Http.dll b/SendGrid/SendGridMail/lib/CodeScales.Http.dll Binary files differindex 2509b52..2509b52 100755 --- a/SendGrid/packages/CodeScales.Http.dll +++ b/SendGrid/SendGridMail/lib/CodeScales.Http.dll diff --git a/SendGrid/Tests/TestSendgrid.cs b/SendGrid/Tests/TestSendgrid.cs index 22e8bb7..95604d3 100755 --- a/SendGrid/Tests/TestSendgrid.cs +++ b/SendGrid/Tests/TestSendgrid.cs @@ -1,7 +1,9 @@ using System;
using System.Collections.Generic;
using System.Globalization;
+using System.IO;
using System.Linq;
+using System.Net.Mail;
using System.Text;
using NUnit.Framework;
using SendGridMail;
@@ -160,11 +162,11 @@ namespace Tests {
var header = new Header();
var sendgrid = new SendGrid(header);
- var text = "hello world";
- sendgrid.EnableClickTracking(text);
+ bool includePlainText = true;
+ sendgrid.EnableClickTracking(includePlainText);
String json = header.AsJson();
- Assert.AreEqual("{\"filters\" : {\"clicktrack\" : {\"settings\" : {\"enable\" : \"1\",\"text\" : \"hello world\"}}}}", json);
+ Assert.AreEqual("{\"filters\" : {\"clicktrack\" : {\"settings\" : {\"enable\" : \"1\",\"enable_text\" : \"1\"}}}}", json);
}
[Test]
@@ -178,7 +180,7 @@ namespace Tests sendgrid.EnableSpamCheck(score, url);
String json = header.AsJson();
- Assert.AreEqual("{\"filters\" : {\"spamcheck\" : {\"settings\" : {\"enable\" : \"1\",\"score\" : \"5\",\"url\" : \"http:\\/\\/www.example.com\"}}}}", json);
+ Assert.AreEqual("{\"filters\" : {\"spamcheck\" : {\"settings\" : {\"enable\" : \"1\",\"maxscore\" : \"5\",\"url\" : \"http:\\/\\/www.example.com\"}}}}", json);
}
[Test]
@@ -189,20 +191,34 @@ namespace Tests var text = "<% %>";
var html = "<% name %>";
- var replace = "John";
- var url = "http://www.example.com";
- var landing = "this_landing";
- sendgrid.EnableUnsubscribe(text, html, replace, url, landing);
- var jsonText = "\"text\" : \""+text+"\"";
- var jsonHtml = "\"html\" : \""+html+"\"";
- var jsonReplace = "\"replace\" : \""+replace+"\"";
- var jsonUrl = "\"url\" : \"http:\\/\\/www.example.com\"";
- var jsonLanding = "\"landing\" : \""+landing+"\"";
+ var jsonText = "\"text\\/plain\" : \"" + text + "\"";
+ var jsonHtml = "\"text\\/html\" : \"" + html + "\"";
+
+ sendgrid.EnableUnsubscribe(text, html);
String json = header.AsJson();
Assert.AreEqual("{\"filters\" : {\"subscriptiontrack\" : {\"settings\" : {\"enable\" : \"1\","+
- jsonText+","+jsonHtml+","+jsonReplace+","+jsonUrl+","+jsonLanding+"}}}}", json);
+ jsonText+","+jsonHtml+"}}}}", json);
+
+ header = new Header();
+ sendgrid = new SendGrid(header);
+
+ var replace = "John";
+ var jsonReplace = "\"replace\" : \"" + replace + "\"";
+
+ sendgrid.EnableUnsubscribe(replace);
+
+ json = header.AsJson();
+ Assert.AreEqual("{\"filters\" : {\"subscriptiontrack\" : {\"settings\" : {\"enable\" : \"1\"," + jsonReplace + "}}}}", json);
+
+ text = "bad";
+ html = "<% name %>";
+ Assert.Throws<Exception>(delegate { sendgrid.EnableUnsubscribe(text, html); });
+
+ text = "<% %>";
+ html = "bad";
+ Assert.Throws<Exception>(delegate { sendgrid.EnableUnsubscribe(text, html); });
}
@@ -219,7 +235,7 @@ namespace Tests sendgrid.EnableFooter(text, html);
String json = header.AsJson();
- Assert.AreEqual("{\"filters\" : {\"footer\" : {\"settings\" : {\"enable\" : \"1\",\"text\" : \""+text+"\",\"html\" : \""+escHtml+"\"}}}}", json);
+ Assert.AreEqual("{\"filters\" : {\"footer\" : {\"settings\" : {\"enable\" : \"1\",\"text\\/plain\" : \""+text+"\",\"text\\/html\" : \""+escHtml+"\"}}}}", json);
}
[Test]
@@ -236,11 +252,11 @@ namespace Tests sendgrid.EnableGoogleAnalytics(source, medium, term, content, campaign);
- var jsonSource = "\"source\" : \"SomeDomain.com\"";
- var jsonMedium = "\"medium\" : \""+medium+"\"";
- var jsonTerm = "\"term\" : \""+term+"\"";
- var jsonContent = "\"content\" : \""+content+"\"";
- var jsonCampaign = "\"campaign\" : \""+campaign+"\"";
+ var jsonSource = "\"utm_source\" : \"SomeDomain.com\"";
+ var jsonMedium = "\"utm_medium\" : \"" + medium + "\"";
+ var jsonTerm = "\"utm_term\" : \"" + term + "\"";
+ var jsonContent = "\"utm_content\" : \"" + content + "\"";
+ var jsonCampaign = "\"utm_campaign\" : \"" + campaign + "\"";
String json = header.AsJson();
Assert.AreEqual("{\"filters\" : {\"ganalytics\" : {\"settings\" : {\"enable\" : \"1\","+
@@ -258,7 +274,10 @@ namespace Tests sendgrid.EnableTemplate(html);
String json = header.AsJson();
- Assert.AreEqual("{\"filters\" : {\"template\" : {\"settings\" : {\"enable\" : \"1\",\"html\" : \""+escHtml+"\"}}}}", json);
+ Assert.AreEqual("{\"filters\" : {\"template\" : {\"settings\" : {\"enable\" : \"1\",\"text\\/html\" : \""+escHtml+"\"}}}}", json);
+
+ escHtml = "bad";
+ Assert.Throws<Exception>(delegate { sendgrid.EnableTemplate(escHtml); });
}
[Test]
@@ -285,5 +304,42 @@ namespace Tests String json = header.AsJson();
Assert.AreEqual("{\"filters\" : {\"bypass_list_management\" : {\"settings\" : {\"enable\" : \"1\"}}}}", json);
}
+
+ [Test]
+ public void CreateMimeMessage()
+ {
+ var message = SendGrid.GetInstance();
+ var attachment = System.IO.Path.GetTempFileName();
+ var text = "this is a test";
+ var html = "<b>This<\b> is a better test";
+ var headers = new KeyValuePair<String, String>("custom", "header");
+ message.AddAttachment(attachment);
+ message.Text = text;
+ message.Html = html;
+ message.AddTo("foo@bar.com");
+ message.From = new MailAddress("foo@bar.com");
+ message.AddHeaders(new Dictionary<string, string>{{headers.Key, headers.Value}});
+ message.EnableGravatar();
+
+ var mime = message.CreateMimeMessage();
+
+ var sr = new StreamReader(mime.AlternateViews[0].ContentStream);
+ var result = sr.ReadToEnd();
+ Assert.AreEqual(text, result);
+
+ sr = new StreamReader(mime.AlternateViews[1].ContentStream);
+ result = sr.ReadToEnd();
+ Assert.AreEqual(html, result);
+
+ result = mime.Headers.Get(headers.Key);
+ Assert.AreEqual(headers.Value, result);
+
+ result = mime.Headers.Get("X-Smtpapi");
+ var expected = "{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}";
+ Assert.AreEqual(expected, result);
+
+ result = mime.Attachments[0].Name;
+ Assert.AreEqual(Path.GetFileName(attachment), result);
+ }
}
}
diff --git a/SendGrid/Tests/TestUtils.cs b/SendGrid/Tests/TestUtils.cs new file mode 100755 index 0000000..48febcf --- /dev/null +++ b/SendGrid/Tests/TestUtils.cs @@ -0,0 +1,38 @@ +using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using SendGridMail;
+
+namespace Tests
+{
+ [TestFixture]
+ public class TestUtils
+ {
+ [Test]
+ public void TestSerialize()
+ {
+ var testcase = "foo";
+ String result = Utils.Serialize(testcase);
+ Assert.AreEqual("\"foo\"", result);
+
+ var testcase2 = 1;
+ result = Utils.Serialize(testcase2);
+ Assert.AreEqual("1", result);
+ }
+
+ [Test]
+ public void TestSerializeDictionary()
+ {
+ var test = new Dictionary<string, string>
+ {
+ {"a", "b"},
+ {"c", "d/e"}
+ };
+ var result = Utils.SerializeDictionary(test);
+ var expected = "{\"a\":\"b\",\"c\":\"d\\/e\"}";
+ Assert.AreEqual(expected, result);
+ }
+ }
+}
diff --git a/SendGrid/Tests/Tests.csproj b/SendGrid/Tests/Tests.csproj index 8009274..cd43bd1 100755 --- a/SendGrid/Tests/Tests.csproj +++ b/SendGrid/Tests/Tests.csproj @@ -58,6 +58,7 @@ <Compile Include="TestSendgrid.cs" />
<Compile Include="TestSendgridMessageSetup.cs" />
<Compile Include="TestTreeNode.cs" />
+ <Compile Include="TestUtils.cs" />
<Compile Include="Transport\TestREST.cs" />
<Compile Include="Transport\TestSMTP.cs" />
</ItemGroup>
diff --git a/SendGrid/Tests/Transport/TestREST.cs b/SendGrid/Tests/Transport/TestREST.cs index ccbab48..e9cc909 100755 --- a/SendGrid/Tests/Transport/TestREST.cs +++ b/SendGrid/Tests/Transport/TestREST.cs @@ -1,8 +1,13 @@ using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net;
+using System.Net.Mail;
using System.Text;
+using Moq;
using NUnit.Framework;
+using SendGridMail;
+using SendGridMail.Transport;
namespace Tests.Transport
{
@@ -10,15 +15,53 @@ namespace Tests.Transport class TestREST
{
[Test]
- public void TestDeliver()
+ public void TestFetchFileBodies()
{
-
+ var test = REST.GetInstance(new NetworkCredential("foo", "bar"));
+ var message = new Mock<ISendGrid>();
+ message.SetupProperty(foo => foo.Attachments, null);
+ var result = test.FetchFileBodies(message.Object);
+ Assert.AreEqual(0, result.Count);
+
+ message.SetupProperty(foo => foo.Attachments, new string[] {"foo", "bar", "raz"});
+ result = test.FetchFileBodies(message.Object);
+ Assert.AreEqual(3, result.Count);
+ Assert.AreEqual(result[0].Key, "foo");
+ Assert.AreEqual(result[1].Key, "bar");
+ Assert.AreEqual(result[2].Key, "raz");
+ Assert.AreEqual(result[0].Value.Name, "foo");
+ Assert.AreEqual(result[1].Value.Name, "bar");
+ Assert.AreEqual(result[2].Value.Name, "raz");
}
[Test]
- public void TestConstructor()
+ public void TestFetchFormParams()
{
-
+ var bar = REST.GetInstance(new NetworkCredential("usr", "psswd"));
+ var message = SendGrid.GetInstance();
+ message.AddTo("foo@bar.com");
+ message.AddCc("cc@bar.com");
+ message.AddBcc("bcc@bar.com");
+ message.From = new MailAddress("from@raz.com");
+ message.Subject = "subject";
+ message.Text = "text";
+ message.Html = "html";
+ message.AddHeaders(new Dictionary<string, string>{{"headerkey", "headervalue"}});
+ message.Header.SetCategory("cat");
+
+ var result = bar.FetchFormParams(message);
+ Assert.True(result.Any(r => r.Key == "api_user" && r.Value == "usr"));
+ Assert.True(result.Any(r => r.Key == "api_key" && r.Value == "psswd"));
+ Assert.True(result.Any(r => r.Key == "to[]" && r.Value == "foo@bar.com"));
+ Assert.True(result.Any(r => r.Key == "cc[]" && r.Value == "cc@bar.com"));
+ Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == "bcc@bar.com"));
+ Assert.True(result.Any(r => r.Key == "from" && r.Value == "from@raz.com"));
+ Assert.True(result.Any(r => r.Key == "subject" && r.Value == "subject"));
+ Assert.True(result.Any(r => r.Key == "text" && r.Value == "text"));
+ Assert.True(result.Any(r => r.Key == "html" && r.Value == "html"));
+ Assert.True(result.Any(r => r.Key == "headers" && r.Value == "{\"headerkey\":\"headervalue\"}"));
+ Assert.True(result.Any(r => r.Key == "x-smtpapi" && r.Value == "{\"category\" : \"cat\"}"));
+ Assert.True(result.Any(r => r.Key == "html" && r.Value == "html"));
}
}
}
diff --git a/SendGrid/Tests/Transport/TestSMTP.cs b/SendGrid/Tests/Transport/TestSMTP.cs index e0e4fe5..3c17008 100755 --- a/SendGrid/Tests/Transport/TestSMTP.cs +++ b/SendGrid/Tests/Transport/TestSMTP.cs @@ -23,7 +23,7 @@ namespace Tests.Transport mockClient.Setup(foo => foo.Send(mime));
var client = mockClient.Object;
var credentials = new NetworkCredential("username", "password");
- var test = SMTP.GenerateInstance(client, credentials);
+ var test = SMTP.GetInstance(client, credentials);
test.Deliver(message);
mockClient.Verify(foo => foo.Send(mime), Times.Once());
@@ -38,14 +38,14 @@ namespace Tests.Transport mock.SetupProperty(foo => foo.EnableSsl);
var client = mock.Object;
var credentials = new NetworkCredential("username", "password");
- var test = SMTP.GenerateInstance(client, credentials);
+ var test = SMTP.GetInstance(client, credentials);
mock.Verify(foo => foo.EnableSsl, Times.Never());
mock = new Mock<SMTP.ISmtpClient>();
mock.SetupProperty(foo => foo.EnableSsl);
client = mock.Object;
credentials = new NetworkCredential("username", "password");
- test = SMTP.GenerateInstance(client, credentials, port:SMTP.SslPort);
+ test = SMTP.GetInstance(client, credentials, port:SMTP.SslPort);
mock.VerifySet(foo => foo.EnableSsl = true);
mock = new Mock<SMTP.ISmtpClient>();
@@ -54,7 +54,7 @@ namespace Tests.Transport credentials = new NetworkCredential("username", "password");
try
{
- test = SMTP.GenerateInstance(client, credentials, port: SMTP.TlsPort);
+ test = SMTP.GetInstance(client, credentials, port: SMTP.TlsPort);
Assert.Fail("should have thrown an unsupported port exception");
}
catch (NotSupportedException ex)
|