summaryrefslogtreecommitdiffstats
path: root/SendGrid/SendGridMail/SendGrid.cs
blob: cc87ffd495d3489091c2e7085b8eaf706fb180e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using Smtpapi;

namespace SendGridMail
{
	public class SendGrid : ISendGrid
	{
		#region constants/vars
		
		//apps list and settings
		private const String ReText = @"<\%\s*\%>";
		private const String ReHtml = @"<\%\s*[^\s]+\s*\%>";
		private static readonly Dictionary<String, String> Filters = InitializeFilters();
		private readonly MailMessage _message;

		#endregion

		#region Initialization and Constructors

		internal SendGrid(MailAddress from, MailAddress[] to, MailAddress[] cc, MailAddress[] bcc,
			String subject, String html, String text, IHeader header = null) : this(header)
		{
			From = from;
			To = to;
			Cc = cc;
			Bcc = bcc;

			_message.Subject = subject;

			Text = text;
			Html = html;
		}

		internal SendGrid(IHeader header)
		{
			_message = new MailMessage();
			Header = header;
			Headers = new Dictionary<string, string>();
		}

		/// <summary>
		///     Creates an instance of SendGrid's custom message object
		/// </summary>
		/// <returns></returns>
		public static SendGrid GetInstance()
		{
			var header = new Header();
			return new SendGrid(header);
		}

		/// <summary>
		///     Creates an instance of SendGrid's custom message object with mail parameters
		/// </summary>
		/// <param name="from">The email address of the sender</param>
		/// <param name="to">An array of the recipients</param>
		/// <param name="cc">Supported over SMTP, with future plans for support in the Web transport</param>
		/// <param name="bcc">Blind recipients</param>
		/// <param name="subject">The subject of the message</param>
		/// <param name="html">the html content for the message</param>
		/// <param name="text">the plain text part of the message</param>
		/// <returns></returns>
		public static SendGrid GetInstance(MailAddress from, MailAddress[] to, MailAddress[] cc, MailAddress[] bcc,
			String subject, String html, String text)
		{
			var header = new Header();
			return new SendGrid(from, to, cc, bcc, subject, html, text, header);
		}

		private static Dictionary<string, string> InitializeFilters()
		{
			return
				new Dictionary<string, string>
				{
					{"Gravatar", "gravatar"},
					{"OpenTracking", "opentrack"},
					{"ClickTracking", "clicktrack"},
					{"SpamCheck", "spamcheck"},
					{"Unsubscribe", "subscriptiontrack"},
					{"Footer", "footer"},
					{"GoogleAnalytics", "ganalytics"},
					{"Template", "template"},
					{"Bcc", "bcc"},
					{"BypassListManagement", "bypass_list_management"}
				};
		}

		#endregion

		#region Properties

		public MailAddress From
		{
			get { return _message.From; }
			set { if (value != null) _message.From = value; }
		}

		public MailAddress[] ReplyTo
		{
			get { return _message.ReplyToList.ToArray(); }
			set
			{
				_message.ReplyToList.Clear();
				foreach (var replyTo in value)
				{
					_message.ReplyToList.Add(replyTo);
				}
			}
		}

		public MailAddress[] To
		{
			get { return _message.To.ToArray(); }
			set
			{
				_message.To.Clear();
				foreach (var mailAddress in value)
				{
					_message.To.Add(mailAddress);
				}
			}
		}

		public MailAddress[] Cc
		{
			get { return _message.CC.ToArray(); }
			set
			{
				_message.CC.Clear();
				foreach (var mailAddress in value)
				{
					_message.CC.Add(mailAddress);
				}
			}
		}

		public MailAddress[] Bcc
		{
			get { return _message.Bcc.ToArray(); }
			set
			{
				_message.Bcc.Clear();
				foreach (var mailAddress in value)
				{
					_message.Bcc.Add(mailAddress);
				}
			}
		}

		public String Subject
		{
			get { return _message.Subject; }
			set { if (value != null) _message.Subject = value; }
		}

		public Dictionary<String, String> Headers { get; set; }
		public IHeader Header { get; set; }
		public String Html { get; set; }
		public String Text { get; set; }

		#endregion

		#region Methods for setting data

		private List<String> _attachments = new List<String>();
		private Dictionary<String, MemoryStream> _streamedAttachments = new Dictionary<string, MemoryStream>();

		public void AddTo(String address)
		{
			var mailAddress = new MailAddress(address);
			_message.To.Add(mailAddress);
		}

		public void AddTo(IEnumerable<String> addresses)
		{
			if (addresses == null) return;

			foreach (var address in addresses.Where(address => address != null))
				AddTo(address);
		}

		public void AddTo(IDictionary<String, IDictionary<String, String>> addresssInfo)
		{
			foreach (var mailAddress in from address in addresssInfo.Keys let table = addresssInfo[address] select new MailAddress(address, table.ContainsKey("DisplayName") ? table["DisplayName"] : null))
			{
				_message.To.Add(mailAddress);
			}
		}

		public void AddCc(String address)
		{
			var mailAddress = new MailAddress(address);
			_message.CC.Add(mailAddress);
		}

		public void AddCc(IEnumerable<String> addresses)
		{
			if (addresses == null) return;
			foreach (var address in addresses.Where(address => address != null))
			{
				AddCc(address);
			}
		}

		public void AddCc(IDictionary<String, IDictionary<String, String>> addresssInfo)
		{
			foreach (var mailAddress in from address in addresssInfo.Keys let table = addresssInfo[address] select new MailAddress(address, table.ContainsKey("DisplayName") ? table["DisplayName"] : null))
			{
				_message.CC.Add(mailAddress);
			}
		}

		public void AddBcc(String address)
		{
			var mailAddress = new MailAddress(address);
			_message.Bcc.Add(mailAddress);
		}

		public void AddBcc(IEnumerable<String> addresses)
		{
			if (addresses == null) return;
			foreach (var address in addresses.Where(address => address != null))
			{
				AddBcc(address);
			}
		}

		public void AddBcc(IDictionary<String, IDictionary<String, String>> addresssInfo)
		{
			foreach (var mailAddress in from address in addresssInfo.Keys let table = addresssInfo[address] select new MailAddress(address, table.ContainsKey("DisplayName") ? table["DisplayName"] : null))
			{
				_message.Bcc.Add(mailAddress);
			}
		}

		public Dictionary<String, MemoryStream> StreamedAttachments
		{
			get { return _streamedAttachments; }
			set { _streamedAttachments = value; }
		}

		public String[] Attachments
		{
			get { return _attachments.ToArray(); }
			set { _attachments = value.ToList(); }
		}

		public void AddSubstitution(String replacementTag, List<String> substitutionValues)
		{
			//let the system complain if they do something bad, since the function returns null
			Header.AddSubstitution(replacementTag, substitutionValues);
		}

		public void AddUniqueArgs(IDictionary<String, String> identifiers)
		{
			Header.AddUniqueArgs(identifiers);
		}

		public void SetCategory(String category)
		{
			Header.SetCategory(category);
		}

		public void SetCategories(IEnumerable<string> categories)
		{
			Header.SetCategories(categories);
		}

		public void AddAttachment(Stream stream, String name)
		{
			var ms = new MemoryStream();
			stream.CopyTo(ms);
			ms.Seek(0, SeekOrigin.Begin);
			StreamedAttachments[name] = ms;
		}

		public void AddAttachment(String filePath)
		{
			_attachments.Add(filePath);
		}

		public IEnumerable<String> GetRecipients()
		{
			var tos = _message.To.ToList();
			var ccs = _message.CC.ToList();
			var bccs = _message.Bcc.ToList();

			var rcpts = tos.Union(ccs.Union(bccs)).Select(address => address.Address);
			return rcpts;
		}

		public void AddHeaders(IDictionary<string, string> headers)
		{
			headers.Keys.ToList().ForEach(key => Headers[key] = headers[key]);
		}

		#endregion

		#region SMTP API Functions

		public void DisableGravatar()
		{
			Header.DisableFilter(Filters["Gravatar"]);
		}

		public void DisableOpenTracking()
		{
			Header.DisableFilter(Filters["OpenTracking"]);
		}

		public void DisableClickTracking()
		{
			Header.DisableFilter(Filters["ClickTracking"]);
		}

		public void DisableSpamCheck()
		{
			Header.DisableFilter(Filters["SpamCheck"]);
		}

		public void DisableUnsubscribe()
		{
			Header.DisableFilter(Filters["Unsubscribe"]);
		}

		public void DisableFooter()
		{
			Header.DisableFilter(Filters["Footer"]);
		}

		public void DisableGoogleAnalytics()
		{
			Header.DisableFilter(Filters["GoogleAnalytics"]);
		}

		public void DisableTemplate()
		{
			Header.DisableFilter(Filters["Template"]);
		}

		public void DisableBcc()
		{
			Header.DisableFilter(Filters["Bcc"]);
		}

		public void DisableBypassListManagement()
		{
			Header.DisableFilter(Filters["BypassListManagement"]);
		}

		public void EnableGravatar()
		{
			Header.EnableFilter(Filters["Gravatar"]);
		}

		public void EnableOpenTracking()
		{
			Header.EnableFilter(Filters["OpenTracking"]);
		}

		public void EnableClickTracking(bool includePlainText = false)
		{
			var filter = Filters["ClickTracking"];

			Header.EnableFilter(filter);
			if (includePlainText)
			{
				Header.AddFilterSetting(filter, new List<string> {"enable_text"}, "1");
			}
		}

		public void EnableSpamCheck(int score = 5, string url = null)
		{
			var filter = Filters["SpamCheck"];

			Header.EnableFilter(filter);
			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)
		{
			var filter = Filters["Unsubscribe"];

			if (!Regex.IsMatch(text, ReText))
			{
				throw new Exception("Missing substitution replacementTag in text");
			}

			if (!Regex.IsMatch(html, ReHtml))
			{
				throw new Exception("Missing substitution replacementTag in html");
			}

			Header.EnableFilter(filter);
			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.EnableFilter(filter);
			Header.AddFilterSetting(filter, new List<string> {"replace"}, replace);
		}

		public void EnableFooter(string text = null, string html = null)
		{
			var filter = Filters["Footer"];

			Header.EnableFilter(filter);
			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 = Filters["GoogleAnalytics"];

			Header.EnableFilter(filter);
			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 = Filters["Template"];

			if (!Regex.IsMatch(html, ReHtml))
			{
				throw new Exception("Missing substitution replacementTag in html");
			}

			Header.EnableFilter(filter);
			Header.AddFilterSetting(filter, new List<string> {"text/html"}, html);
		}

		public void EnableBcc(string email)
		{
			var filter = Filters["Bcc"];

			Header.EnableFilter(filter);
			Header.AddFilterSetting(filter, new List<string> {"email"}, email);
		}

		public void EnableBypassListManagement()
		{
			Header.EnableFilter(Filters["BypassListManagement"]);
		}

		#endregion

		public MailMessage CreateMimeMessage()
		{
			var smtpapi = Header.JsonString();

			if (!String.IsNullOrEmpty(smtpapi))
				_message.Headers.Add("X-Smtpapi", smtpapi);

			Headers.Keys.ToList().ForEach(k => _message.Headers.Add(k, Headers[k]));

			_message.Attachments.Clear();
			_message.AlternateViews.Clear();

			if (Attachments != null)
			{
				foreach (var attachment in Attachments)
				{
					_message.Attachments.Add(new Attachment(attachment, MediaTypeNames.Application.Octet));
				}
			}

			if (StreamedAttachments != null)
			{
				foreach (var attachment in StreamedAttachments)
				{
					attachment.Value.Position = 0;
					_message.Attachments.Add(new Attachment(attachment.Value, attachment.Key));
				}
			}

			if (Text != null)
			{
				var plainView = AlternateView.CreateAlternateViewFromString(Text, null, "text/plain");
				_message.AlternateViews.Add(plainView);
			}

			if (Html == null) return _message;

			var htmlView = AlternateView.CreateAlternateViewFromString(Html, null, "text/html");
			_message.AlternateViews.Add(htmlView);

			//message.SubjectEncoding = Encoding.GetEncoding(charset);
			//message.BodyEncoding = Encoding.GetEncoding(charset);

			return _message;
		}

		/// <summary>
		///     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)
		{
			var client = new SmtpClient("localhost")
			{
				DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
				PickupDirectoryLocation = @"C:\temp"
			};
			var msg = CreateMimeMessage();
			client.Send(msg);
		}
	}
}