forked from sendgrid/sendgrid-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSendGridMessage.cs
1240 lines (1099 loc) · 58 KB
/
SendGridMessage.cs
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <copyright file="SendGridMessage.cs" company="Twilio SendGrid">
// Copyright (c) Twilio SendGrid. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using Newtonsoft.Json;
using SendGrid.Helpers.Mail.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SendGrid.Helpers.Mail
{
/// <summary>
/// Class SendGridMessage builds an object that sends an email through Twilio SendGrid.
/// </summary>
[JsonObject(IsReference = false)]
public class SendGridMessage
{
/// <summary>
/// Gets or sets an email object containing the email address and name of the sender. Unicode encoding is not supported for the from field.
/// </summary>
[JsonProperty(PropertyName = "from")]
public EmailAddress From { get; set; }
/// <summary>
/// Gets or sets the subject of your email. This may be overridden by personalizations[x].subject.
/// </summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
/// <summary>
/// Gets or sets a list of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. For more information, please see our documentation on Personalizations. Parameters in personalizations will override the parameters of the same name from the message level.
/// https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html.
/// </summary>
[JsonProperty(PropertyName = "personalizations", IsReference = false)]
public List<Personalization> Personalizations { get; set; }
/// <summary>
/// Gets or sets a list in which you may specify the content of your email. You can include multiple mime types of content, but you must specify at least one. To include more than one mime type, simply add another object to the array containing the type and value parameters. If included, text/plain and text/html must be the first indices of the array in this order. If you choose to include the text/plain or text/html mime types, they must be the first indices of the content array in the order text/plain, text/html.*Content is NOT mandatory if you using a transactional template and have defined the template_id in the Request.
/// </summary>
[JsonProperty(PropertyName = "content", IsReference = false)]
public List<Content> Contents { get; set; }
/// <summary>
/// Gets or sets a Content object with a Mime Type of text/plain.
/// </summary>
[JsonIgnore]
public string PlainTextContent { get; set; }
/// <summary>
/// Gets or sets a Content object with a Mime Type of text/html.
/// </summary>
[JsonIgnore]
public string HtmlContent { get; set; }
/// <summary>
/// Gets or sets a list of objects in which you can specify any attachments you want to include.
/// </summary>
[JsonProperty(PropertyName = "attachments", IsReference = false)]
public List<Attachment> Attachments { get; set; }
/// <summary>
/// Gets or sets the id of a template that you would like to use. If you use a template that contains content and a subject (either text or html), you do not need to specify those in the respective personalizations or message level parameters.
/// </summary>
[JsonProperty(PropertyName = "template_id")]
public string TemplateId { get; set; }
/// <summary>
/// Gets or sets an object containing key/value pairs of header names and the value to substitute for them. You must ensure these are properly encoded if they contain unicode characters. Must not be any of the following reserved headers: x-sg-id, x-sg-eid, received, dkim-signature, Content-Type, Content-Transfer-Encoding, To, From, Subject, Reply-To, CC, BCC.
/// </summary>
[JsonProperty(PropertyName = "headers", IsReference = false)]
public Dictionary<string, string> Headers { get; set; }
/// <summary>
/// Gets or sets an object of key/value pairs that define large blocks of content that can be inserted into your emails using substitution tags.
/// </summary>
[JsonProperty(PropertyName = "sections", IsReference = false)]
public Dictionary<string, string> Sections { get; set; }
/// <summary>
/// Gets or sets a list of category names for this message. Each category name may not exceed 255 characters. You cannot have more than 10 categories per request.
/// </summary>
[JsonProperty(PropertyName = "categories", IsReference = false)]
public List<string> Categories { get; set; }
/// <summary>
/// Gets or sets values that are specific to the entire send that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by any conflicting personalizations[x].custom_args if that parameter has been defined. If personalizations[x].custom_args has been defined but does not conflict with the values defined within this parameter, the two will be merged. The combined total size of these custom arguments may not exceed 10,000 bytes.
/// </summary>
[JsonProperty(PropertyName = "custom_args", IsReference = false)]
public Dictionary<string, string> CustomArgs { get; set; }
/// <summary>
/// Gets or sets a unix timestamp allowing you to specify when you want your email to be sent from SendGrid. This is not necessary if you want the email to be sent at the time of your API request.
/// </summary>
[JsonProperty(PropertyName = "send_at")]
public long? SendAt { get; set; }
/// <summary>
/// Gets or sets an object allowing you to specify how to handle unsubscribes.
/// </summary>
[JsonProperty(PropertyName = "asm")]
public ASM Asm { get; set; }
/// <summary>
/// Gets or sets an ID that represents a batch of emails (AKA multiple sends of the same email) to be associated to each other for scheduling. Including a batch_id in your request allows you to include this email in that batch, and also enables you to cancel or pause the delivery of that entire batch. For more information, please read about Cancel Scheduled Sends.
/// https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html.
/// </summary>
[JsonProperty(PropertyName = "batch_id")]
public string BatchId { get; set; }
/// <summary>
/// Gets or sets the IP Pool that you would like to send this email from.
/// </summary>
[JsonProperty(PropertyName = "ip_pool_name")]
public string IpPoolName { get; set; }
/// <summary>
/// Gets or sets a collection of different mail settings that you can use to specify how you would like this email to be handled.
/// </summary>
[JsonProperty(PropertyName = "mail_settings")]
public MailSettings MailSettings { get; set; }
/// <summary>
/// Gets or sets settings to determine how you would like to track the metrics of how your recipients interact with your email.
/// </summary>
[JsonProperty(PropertyName = "tracking_settings")]
public TrackingSettings TrackingSettings { get; set; }
/// <summary>
/// Gets or sets an email object containing the email address and name of the individual who should receive responses to your email.
/// </summary>
[JsonProperty(PropertyName = "reply_to")]
public EmailAddress ReplyTo { get; set; }
/// <summary>
/// Gets or sets a list of objects of email objects containing the email address and name of the individuals who should receive responses to your email.
/// </summary>
[JsonProperty(PropertyName = "reply_to_list", IsReference = false)]
public List<EmailAddress> ReplyTos { get; set; }
/// <summary>
/// Add a recipient email.
/// </summary>
/// <param name="email">Specify the recipient's email.</param>
/// <param name="name">Specify the recipient's name.</param>
public void AddTo(string email, string name = null)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email");
this.AddTo(new EmailAddress(email, name));
}
/// <summary>
/// Add a recipient email.
/// </summary>
/// <param name="email">An email recipient that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the recipient email.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddTo(EmailAddress email, int personalizationIndex = 0, Personalization personalization = null)
{
if (email == null)
throw new ArgumentNullException("email");
AddTos(new List<EmailAddress> { email }, personalizationIndex, personalization);
}
/// <summary>
/// Add recipient emails.
/// </summary>
/// <param name="emails">A list of recipients. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the recipient emails.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddTos(List<EmailAddress> emails, int personalizationIndex = 0, Personalization personalization = null)
{
if (emails == null)
throw new ArgumentNullException("emails");
if (emails.Count == 0)
throw new InvalidOperationException("Sequence contains no elements");
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Tos = personalization.Tos ?? new List<EmailAddress>();
personalization.Tos.AddRange(emails);
}
/// <summary>
/// Add a cc email recipient.
/// </summary>
/// <param name="email">Specify the recipient's email.</param>
/// <param name="name">Specify the recipient's name.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null or whitespace</exception>
public void AddCc(string email, string name = null)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email");
this.AddCc(new EmailAddress(email, name));
}
/// <summary>
/// Add a cc email recipient.
/// </summary>
/// <param name="email">An email recipient that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the cc email.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null</exception>
public void AddCc(EmailAddress email, int personalizationIndex = 0, Personalization personalization = null)
{
if (email == null)
throw new ArgumentNullException("email");
AddCcs(new List<EmailAddress> { email }, personalizationIndex, personalization);
}
/// <summary>
/// Add cc recipient emails.
/// </summary>
/// <param name="emails">A list of cc recipients. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the cc emails.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the emails parameter is null</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the emails parameter is empty</exception>
public void AddCcs(List<EmailAddress> emails, int personalizationIndex = 0, Personalization personalization = null)
{
if (emails == null)
throw new ArgumentNullException("emails");
if (emails.Count == 0)
throw new InvalidOperationException("Sequence contains no elements");
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Ccs = personalization.Ccs ?? new List<EmailAddress>();
personalization.Ccs.AddRange(emails);
}
/// <summary>
/// Add a bcc recipient emails.
/// </summary>
/// <param name="email">Specify the recipient's email.</param>
/// <param name="name">Specify the recipient's name.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null or whitespace</exception>
public void AddBcc(string email, string name = null)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email");
this.AddBcc(new EmailAddress(email, name));
}
/// <summary>
/// Add a bcc recipient emails.
/// </summary>
/// <param name="email">An email recipient that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the bcc email.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null</exception>
public void AddBcc(EmailAddress email, int personalizationIndex = 0, Personalization personalization = null)
{
if (email == null)
throw new ArgumentNullException("email");
AddBccs(new List<EmailAddress> { email }, personalizationIndex, personalization);
}
/// <summary>
/// Add bcc email recipients.
/// </summary>
/// <param name="emails">A list of bcc recipients. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the bcc emails.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the emails parameter is null</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the emails parameter is empty</exception>
public void AddBccs(List<EmailAddress> emails, int personalizationIndex = 0, Personalization personalization = null)
{
if (emails == null)
throw new ArgumentNullException("emails");
if (emails.Count == 0)
throw new InvalidOperationException("Sequence contains no elements");
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Bccs = personalization.Bccs ?? new List<EmailAddress>();
personalization.Bccs.AddRange(emails);
}
/// <summary>
/// Add a subject to the email.
/// </summary>
/// <param name="subject">The subject line of your email.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the subject.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void SetSubject(string subject, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Subject = subject;
}
/// <summary>
/// Add a header to the email.
/// </summary>
/// <param name="headerKey">Header key (e.g. X-Header).</param>
/// <param name="headerValue">Header value.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the header.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddHeader(string headerKey, string headerValue, int personalizationIndex = 0, Personalization personalization = null)
{
AddHeaders(new Dictionary<string, string> { { headerKey, headerValue } }, personalizationIndex, personalization);
}
/// <summary>
/// Add headers to the email.
/// </summary>
/// <param name="headers">A list of Headers.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the headers.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddHeaders(Dictionary<string, string> headers, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Headers = personalization.Headers == null ? headers :
personalization.Headers.Union(headers).ToDictionary(pair => pair.Key, pair => pair.Value);
}
/// <summary>
/// Add a reply-to email.
/// </summary>
/// <param name="email">Specify the recipient's email.</param>
/// <param name="name">Specify the recipient's name.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null or whitespace</exception>
public void AddReplyTo(string email, string name = null)
{
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email");
this.AddReplyTo(new EmailAddress(email, name));
}
/// <summary>
/// Add a reply-to email.
/// </summary>
/// <param name="email">An email recipient that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the email parameter is null</exception>
public void AddReplyTo(EmailAddress email)
{
if (email == null)
throw new ArgumentNullException("email");
AddReplyTos(new List<EmailAddress> { email });
}
/// <summary>
/// Add reply-to recipients.
/// </summary>
/// <param name="emails">A list of reply-to recipients. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the emails parameter is null</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the emails parameter is empty</exception>
public void AddReplyTos(List<EmailAddress> emails)
{
if (emails == null)
throw new ArgumentNullException("emails");
if (emails.Count == 0)
throw new InvalidOperationException("Sequence contains no elements");
if (ReplyTos == null) ReplyTos = new List<EmailAddress>();
ReplyTos.AddRange(emails);
}
/// <summary>
/// Add a substitution to the email.
/// You may not include more than 100 substitutions per personalization object, and the total collective size of your substitutions may not exceed 10,000 bytes per personalization object.
/// </summary>
/// <param name="substitutionKey">The substitution key.</param>
/// <param name="substitutionValue">The substitution value.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the substitution.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddSubstitution(string substitutionKey, string substitutionValue, int personalizationIndex = 0, Personalization personalization = null)
{
AddSubstitutions(new Dictionary<string, string> { { substitutionKey, substitutionValue } }, personalizationIndex, personalization);
}
/// <summary>
/// Add substitutions to the email.
/// </summary>
/// <param name="substitutions">A list of Substitutions.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the substitutions.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddSubstitutions(Dictionary<string, string> substitutions, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.Substitutions = personalization.Substitutions == null ? substitutions :
personalization.Substitutions.Union(substitutions).ToDictionary(pair => pair.Key, pair => pair.Value);
}
/// <summary>
/// Add dynamic template data to the email.
/// </summary>
/// <param name="dynamicTemplateData">A Template Data object.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the substitutions.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void SetTemplateData(object dynamicTemplateData, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.TemplateData = dynamicTemplateData;
}
/// <summary>
/// Add a custom argument to the email.
/// </summary>
/// <param name="customArgKey">The custom argument key.</param>
/// <param name="customArgValue">The custom argument value.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the custom arg.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddCustomArg(string customArgKey, string customArgValue, int personalizationIndex = 0, Personalization personalization = null)
{
AddCustomArgs(new Dictionary<string, string> { { customArgKey, customArgValue } }, personalizationIndex, personalization);
}
/// <summary>
/// Add custom arguments to the email.
/// </summary>
/// <param name="customArgs">A list of CustomArgs.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the custom args.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void AddCustomArgs(Dictionary<string, string> customArgs, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.CustomArgs = personalization.CustomArgs == null ? customArgs :
personalization.CustomArgs.Union(customArgs).ToDictionary(pair => pair.Key, pair => pair.Value);
}
/// <summary>
/// Specify the unix timestamp to specify when you want the email to be sent from Twilio SendGrid.
/// </summary>
/// <param name="sendAt">Specify the unix timestamp for when you want the email to be sent from Twilio SendGrid.</param>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the send at timestamp.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
public void SetSendAt(long sendAt, int personalizationIndex = 0, Personalization personalization = null)
{
personalization = GetPersonalization(personalizationIndex, personalization);
personalization.SendAt = sendAt;
}
/// <summary>
/// Retrieves a Personalization object, adds a pre-created Personalization object, or creates and adds a Personalization object.
/// </summary>
/// <param name="personalizationIndex">Specify the index of the Personalization object where you want to add the send at timestamp.</param>
/// <param name="personalization">A personalization object to append to the message.</param>
/// <returns>The Personalization.</returns>
private Personalization GetPersonalization(int personalizationIndex = 0, Personalization personalization = null)
{
if (personalization != null)
{
if (this.Personalizations == null)
this.Personalizations = new List<Personalization>();
this.Personalizations.Add(personalization);
}
else if (this.Personalizations != null)
{
if (personalizationIndex > this.Personalizations.Count)
throw new ArgumentException("personalizationIndex " + personalizationIndex + " must not be greater than " + this.Personalizations.Count);
if (personalizationIndex == this.Personalizations.Count)
this.Personalizations.Add(new Personalization());
personalization = this.Personalizations[personalizationIndex];
}
else
{
personalization = new Personalization();
this.Personalizations = new List<Personalization>() { personalization };
}
return personalization;
}
/// <summary>
/// Set the from email.
/// </summary>
/// <param name="email">Specify the recipient's email.</param>
/// <param name="name">Specify the recipient's name.</param>
public void SetFrom(string email, string name = null)
{
if (string.IsNullOrWhiteSpace(email))
{
throw new ArgumentNullException("email");
}
this.SetFrom(new EmailAddress(email, name));
}
/// <summary>
/// Set the from email.
/// </summary>
/// <param name="email">An email object containing the email address and name of the sender. Unicode encoding is not supported for the from field.</param>
public void SetFrom(EmailAddress email)
{
this.From = email;
}
/// <summary>
/// Set the reply to email.
/// </summary>
/// <param name="email">An email object containing the email address and name of the individual who should receive responses to your email.</param>
public void SetReplyTo(EmailAddress email)
{
this.ReplyTo = email;
}
/// <summary>
/// Set a global subject line.
/// </summary>
/// <param name="subject">The subject of your email. This may be overridden by personalizations[x].subject.</param>
public void SetGlobalSubject(string subject)
{
this.Subject = subject;
}
/// <summary>
/// Add content to the email.
/// </summary>
/// <param name="mimeType">The mime type of the content you are including in your email. For example, text/plain or text/html.</param>
/// <param name="text">The actual content of the specified mime type that you are including in your email.</param>
public void AddContent(string mimeType, string text)
{
var content = new Content()
{
Type = mimeType,
Value = text,
};
if (this.Contents == null)
{
this.Contents = new List<Content>()
{
content,
};
}
else
{
this.Contents.Add(content);
}
return;
}
/// <summary>
/// Add contents to the email.
/// </summary>
/// <param name="contents">A list of Content.</param>
public void AddContents(List<Content> contents)
{
if (this.Contents == null)
{
this.Contents = new List<Content>();
this.Contents = contents;
}
else
{
this.Contents.AddRange(contents);
}
return;
}
/// <summary>
/// Add an attachment from a stream to the email. No attachment will be added in the case that the stream cannot be read. Streams of length greater than int.MaxValue are truncated.
/// </summary>
/// <param name="filename">The filename the attachment will display in the email.</param>
/// <param name="contentStream">The stream to use as content of the attachment.</param>
/// <param name="type">The mime type of the content you are attaching. For example, application/pdf or image/jpeg.</param>
/// <param name="disposition">The content-disposition of the attachment specifying how you would like the attachment to be displayed. For example, "inline" results in the attached file being displayed automatically within the message while "attachment" results in the attached file requiring some action to be taken before it is displayed (e.g. opening or downloading the file). Defaults to "attachment". Can be either "attachment" or "inline".</param>
/// <param name="content_id">A unique id that you specify for the attachment. This is used when the disposition is set to "inline" and the attachment is an image, allowing the file to be displayed within the body of your email. Ex: <![CDATA[ <img src="cid:ii_139db99fdb5c3704"></img> ]]>.</param>
/// <param name="cancellationToken">A cancellation token which can notify if the task should be canceled.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task AddAttachmentAsync(string filename, Stream contentStream, string type = null, string disposition = null, string content_id = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Stream doesn't want us to read it, can't do anything else here
if (contentStream == null || !contentStream.CanRead)
{
return;
}
var contentLength = Convert.ToInt32(contentStream.Length);
var streamBytes = new byte[contentLength];
await contentStream.ReadAsync(streamBytes, 0, contentLength, cancellationToken);
var base64Content = Convert.ToBase64String(streamBytes);
this.AddAttachment(filename, base64Content, type, disposition, content_id);
}
/// <summary>
/// Add an attachment to the email.
/// </summary>
/// <param name="filename">The filename the attachment will display in the email.</param>
/// <param name="base64Content">The Base64 encoded content of the attachment.</param>
/// <param name="type">The mime type of the content you are attaching. For example, application/pdf or image/jpeg.</param>
/// <param name="disposition">The content-disposition of the attachment specifying how you would like the attachment to be displayed. For example, "inline" results in the attached file being displayed automatically within the message while "attachment" results in the attached file requiring some action to be taken before it is displayed (e.g. opening or downloading the file). Defaults to "attachment". Can be either "attachment" or "inline".</param>
/// <param name="content_id">A unique id that you specify for the attachment. This is used when the disposition is set to "inline" and the attachment is an image, allowing the file to be displayed within the body of your email. Ex: <![CDATA[ <img src="cid:ii_139db99fdb5c3704"></img> ]]>.</param>
public void AddAttachment(string filename, string base64Content, string type = null, string disposition = null, string content_id = null)
{
if (string.IsNullOrWhiteSpace(filename) || string.IsNullOrWhiteSpace(base64Content))
{
return;
}
var attachment = new Attachment
{
Filename = filename,
Content = base64Content,
Type = type,
Disposition = disposition,
ContentId = content_id,
};
this.AddAttachment(attachment);
}
/// <summary>
/// Add an attachment to the email.
/// </summary>
/// <param name="attachment">An Attachment.</param>
public void AddAttachment(Attachment attachment)
{
if (this.Attachments == null)
{
this.Attachments = new List<Attachment>();
}
this.Attachments.Add(attachment);
}
/// <summary>
/// Add attachments to the email.
/// </summary>
/// <param name="attachments">A list of Attachments.</param>
public void AddAttachments(IEnumerable<Attachment> attachments)
{
if (this.Attachments == null)
{
this.Attachments = new List<Attachment>();
}
this.Attachments.AddRange(attachments);
}
/// <summary>
/// Add a template id to the email.
/// </summary>
/// <param name="templateID">The id of a template that you would like to use. If you use a template that contains content and a subject (either text or html), you do not need to specify those in the respective personalizations or message level parameters.</param>
public void SetTemplateId(string templateID)
{
this.TemplateId = templateID;
}
/// <summary>
/// Add a section substitution to the email.
/// </summary>
/// <param name="key">The section key.</param>
/// <param name="value">The section replacement value.</param>
public void AddSection(string key, string value)
{
if (this.Sections == null)
{
this.Sections = new Dictionary<string, string>()
{
{ key, value },
};
}
else
{
this.Sections.Add(key, value);
}
return;
}
/// <summary>
/// Add sections to the email.
/// </summary>
/// <param name="sections">A list of Sections.</param>
public void AddSections(Dictionary<string, string> sections)
{
if (this.Sections == null)
{
this.Sections = sections;
}
else
{
this.Sections = (this.Sections != null)
? this.Sections.Union(sections).ToDictionary(pair => pair.Key, pair => pair.Value) : sections;
}
return;
}
/// <summary>
/// Add a global header to the email.
/// </summary>
/// <param name="key">Header key (e.g. X-Header).</param>
/// <param name="value">Header value.</param>
public void AddGlobalHeader(string key, string value)
{
if (this.Headers == null)
{
this.Headers = new Dictionary<string, string>()
{
{ key, value },
};
}
else
{
this.Headers.Add(key, value);
}
return;
}
/// <summary>
/// Add global headers to the email.
/// </summary>
/// <param name="headers">A list of Headers.</param>
public void AddGlobalHeaders(Dictionary<string, string> headers)
{
if (this.Headers == null)
{
this.Headers = headers;
}
else
{
this.Headers = (this.Headers != null)
? this.Headers.Union(headers).ToDictionary(pair => pair.Key, pair => pair.Value) : headers;
}
return;
}
/// <summary>
/// Add a category to the email.
/// </summary>
/// <param name="category">A category name, not to exceed 255 characters. There is a limit of 10 categories per request.</param>
public void AddCategory(string category)
{
if (this.Categories == null)
{
this.Categories = new List<string>()
{
category,
};
}
else
{
this.Categories.Add(category);
}
return;
}
/// <summary>
/// Add categories to the email.
/// </summary>
/// <param name="categories">A list of Categories.</param>
public void AddCategories(List<string> categories)
{
if (this.Categories == null)
{
this.Categories = new List<string>();
this.Categories = categories;
}
else
{
this.Categories.AddRange(categories);
}
return;
}
/// <summary>
/// Add a global custom argument.
/// </summary>
/// <param name="key">The custom arguments key. The value of this key will be overridden by custom args at the personalization level.</param>
/// <param name="value">The custom argument value.</param>
public void AddGlobalCustomArg(string key, string value)
{
if (this.CustomArgs == null)
{
this.CustomArgs = new Dictionary<string, string>()
{
{ key, value },
};
}
else
{
this.CustomArgs.Add(key, value);
}
return;
}
/// <summary>
/// Add global custom arguments.
/// </summary>
/// <param name="customArgs">A list of CustomArgs.</param>
public void AddGlobalCustomArgs(Dictionary<string, string> customArgs)
{
if (this.CustomArgs == null)
{
this.CustomArgs = customArgs;
}
else
{
this.CustomArgs = (this.CustomArgs != null)
? this.CustomArgs.Union(customArgs).ToDictionary(pair => pair.Key, pair => pair.Value) : customArgs;
}
return;
}
/// <summary>
/// Set the global send at unix timestamp.
/// </summary>
/// <param name="sendAt">A unix timestamp allowing you to specify when you want your email to be sent from Twilio SendGrid. This is not necessary if you want the email to be sent at the time of your API request.</param>
public void SetGlobalSendAt(int sendAt)
{
this.SendAt = sendAt;
}
/// <summary>
/// Set the email's batch id.
/// </summary>
/// <param name="batchId">
/// This ID represents a batch of emails (AKA multiple sends of the same email) to be associated to each other for scheduling. Including a batch_id in your request allows you to include this email in that batch, and also enables you to cancel or pause the delivery of that entire batch. For more information, please read about Cancel Scheduled Sends.
/// https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html.
/// </param>
public void SetBatchId(string batchId)
{
this.BatchId = batchId;
}
/// <summary>
/// Set advanced suppression management (ASM).
/// </summary>
/// <param name="groupID">The unsubscribe group to associate with this email.</param>
/// <param name="groupsToDisplay">
/// An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page.
/// https://sendgrid.com/docs/User_Guide/Suppressions/recipient_subscription_preferences.html.
/// </param>
public void SetAsm(int groupID, List<int> groupsToDisplay = null)
{
this.Asm = new ASM();
this.Asm.GroupId = groupID;
if (groupsToDisplay != null)
{
this.Asm.GroupsToDisplay = groupsToDisplay;
}
return;
}
/// <summary>
/// Set this email's IP Pool.
/// </summary>
/// <param name="ipPoolName">The IP Pool that you would like to send this email from.</param>
public void SetIpPoolName(string ipPoolName)
{
this.IpPoolName = ipPoolName;
}
/// <summary>
/// Set the bcc settings.
/// The address specified in the mail_settings.bcc object will receive a blind carbon copy (BCC) of the very first personalization defined in the personalizations array.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
/// <param name="email">The email address that you would like to receive the BCC.</param>
public void SetBccSetting(bool enable, string email)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.BccSettings = new BCCSettings()
{
Enable = enable,
Email = email,
};
return;
}
/// <summary>
/// Set the bypass list management setting.
/// Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. Ex: outage emails, or forgot password emails.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
public void SetBypassListManagement(bool enable)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.BypassListManagement = new BypassListManagement()
{
Enable = enable,
};
return;
}
/// <summary>
/// Set the bypass spam management setting.
/// Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
public void SetBypassSpamManagement(bool enable)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.BypassSpamManagement = new BypassSpamManagement
{
Enable = enable,
};
return;
}
/// <summary>
/// Set the bypass bounce management setting.
/// Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
public void SetBypassBounceManagement(bool enable)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.BypassBounceManagement = new BypassBounceManagement
{
Enable = enable,
};
return;
}
/// <summary>
/// Set the bypass unsubscribe management setting.
/// Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
public void SetBypassUnsubscribeManagement(bool enable)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.BypassUnsubscribeManagement = new BypassUnsubscribeManagement
{
Enable = enable,
};
return;
}
/// <summary>
/// Set the footer setting.
/// The default footer that you would like appended to the bottom of every email.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
/// <param name="html">The HTML content of your footer.</param>
/// <param name="text">The plain text content of your footer.</param>
public void SetFooterSetting(bool enable, string html = null, string text = null)
{
if (this.MailSettings == null)
{
this.MailSettings = new MailSettings();
}
this.MailSettings.FooterSettings = new FooterSettings()
{
Enable = enable,
Html = html,
Text = text,
};
return;
}
/// <summary>
/// Set the sandbox mode setting.
/// This allows you to send a test email to ensure that your request body is valid and formatted correctly. For more information, please see our Classroom.
/// </summary>
/// <param name="enable">Gets or sets a value indicating whether this setting is enabled.</param>
public void SetSandBoxMode(bool enable)
{
if (this.MailSettings == null)