-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
MimeMessage.cs
3121 lines (2696 loc) · 107 KB
/
MimeMessage.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
//
// MimeMessage.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2017 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
#if PORTABLE
using Encoding = Portable.Text.Encoding;
#endif
#if ENABLE_SNM
using System.Net.Mail;
#endif
#if ENABLE_CRYPTO
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using MimeKit.Cryptography;
#endif
using MimeKit.IO;
using MimeKit.Text;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A MIME message.
/// </summary>
/// <remarks>
/// <para>A message consists of header fields and, optionally, a body.</para>
/// <para>The body of the message can either be plain text or it can be a
/// tree of MIME entities such as a text/plain MIME part and a collection
/// of file attachments.</para>
/// </remarks>
public class MimeMessage
{
static readonly string[] StandardAddressHeaders = {
"Resent-From", "Resent-Reply-To", "Resent-To", "Resent-Cc", "Resent-Bcc",
"From", "Reply-To", "To", "Cc", "Bcc"
};
readonly Dictionary<string, InternetAddressList> addresses;
MessageImportance importance = MessageImportance.Normal;
XMessagePriority xpriority = XMessagePriority.Normal;
MessagePriority priority = MessagePriority.Normal;
readonly RfcComplianceMode compliance;
readonly MessageIdList references;
MailboxAddress resentSender;
DateTimeOffset resentDate;
string resentMessageId;
MailboxAddress sender;
DateTimeOffset date;
string messageId;
string inreplyto;
Version version;
// Note: this .ctor is used only by the MimeParser and MimeMessage.CreateFromMailMessage()
internal MimeMessage (ParserOptions options, IEnumerable<Header> headers, RfcComplianceMode mode)
{
addresses = new Dictionary<string, InternetAddressList> (MimeUtils.OrdinalIgnoreCase);
Headers = new HeaderList (options);
compliance = mode;
// initialize our address lists
foreach (var name in StandardAddressHeaders) {
var list = new InternetAddressList ();
list.Changed += InternetAddressListChanged;
addresses.Add (name, list);
}
references = new MessageIdList ();
references.Changed += ReferencesChanged;
inreplyto = null;
Headers.Changed += HeadersChanged;
// add all of our message headers...
foreach (var header in headers) {
if (header.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase))
continue;
Headers.Add (header);
}
}
internal MimeMessage (ParserOptions options)
{
addresses = new Dictionary<string, InternetAddressList> (MimeUtils.OrdinalIgnoreCase);
Headers = new HeaderList (options);
compliance = RfcComplianceMode.Strict;
// initialize our address lists
foreach (var name in StandardAddressHeaders) {
var list = new InternetAddressList ();
list.Changed += InternetAddressListChanged;
addresses.Add (name, list);
}
references = new MessageIdList ();
references.Changed += ReferencesChanged;
inreplyto = null;
Headers.Changed += HeadersChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimeMessage"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="MimeMessage"/>.
/// </remarks>
/// <param name="args">An array of initialization parameters: headers and message parts.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="args"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="args"/> contains more than one <see cref="MimeKit.MimeEntity"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para>
/// </exception>
public MimeMessage (params object[] args) : this (ParserOptions.Default.Clone ())
{
if (args == null)
throw new ArgumentNullException (nameof (args));
MimeEntity body = null;
foreach (object obj in args) {
if (obj == null)
continue;
// Just add the headers and let the events (already setup) keep the
// addresses in sync.
var header = obj as Header;
if (header != null) {
if (!header.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase))
Headers.Add (header);
continue;
}
var headers = obj as IEnumerable<Header>;
if (headers != null) {
foreach (var h in headers) {
if (!h.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase))
Headers.Add (h);
}
continue;
}
var entity = obj as MimeEntity;
if (entity != null) {
if (body != null)
throw new ArgumentException ("Message body should not be specified more than once.");
body = entity;
continue;
}
throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ());
}
if (body != null)
Body = body;
// Do exactly as in the parameterless constructor but avoid setting a default
// value if an header already provided one.
if (!Headers.Contains (HeaderId.From))
Headers[HeaderId.From] = string.Empty;
if (date == default (DateTimeOffset))
Date = DateTimeOffset.Now;
if (!Headers.Contains (HeaderId.Subject))
Subject = string.Empty;
if (messageId == null)
MessageId = MimeUtils.GenerateMessageId ();
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimeMessage"/> class.
/// </summary>
/// <remarks>
/// Creates a new MIME message, specifying details at creation time.
/// </remarks>
/// <param name="from">The list of addresses in the From header.</param>
/// <param name="to">The list of addresses in the To header.</param>
/// <param name="subject">The subject of the message.</param>
/// <param name="body">The body of the message.</param>
public MimeMessage (IEnumerable<InternetAddress> from, IEnumerable<InternetAddress> to, string subject, MimeEntity body) : this ()
{
From.AddRange (from);
To.AddRange (to);
Subject = subject;
Body = body;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MimeMessage"/> class.
/// </summary>
/// <remarks>
/// Creates a new MIME message.
/// </remarks>
public MimeMessage () : this (ParserOptions.Default.Clone ())
{
Headers[HeaderId.From] = string.Empty;
Date = DateTimeOffset.Now;
Subject = string.Empty;
MessageId = MimeUtils.GenerateMessageId ();
}
/// <summary>
/// Gets or sets the mbox marker.
/// </summary>
/// <remarks>
/// Set by the <see cref="MimeParser"/> when parsing attached message/rfc822 parts
/// so that the message/rfc822 part can be reserialized back to its original form.
/// </remarks>
/// <value>The mbox marker.</value>
internal byte[] MboxMarker {
get; set;
}
/// <summary>
/// Gets the list of headers.
/// </summary>
/// <remarks>
/// <para>Represents the list of headers for a message. Typically, the headers of
/// a message will contain transmission headers such as From and To along
/// with metadata headers such as Subject and Date, but may include just
/// about anything.</para>
/// <para><alert class="tip">To access any MIME headers other than
/// <see cref="HeaderId.MimeVersion"/>, you will need to access the
/// <see cref="MimeEntity.Headers"/> property of the <see cref="Body"/>.
/// </alert></para>
/// </remarks>
/// <value>The list of headers.</value>
public HeaderList Headers {
get; private set;
}
/// <summary>
/// Get or set the value of the Importance header.
/// </summary>
/// <remarks>
/// Gets or sets the value of the Importance header.
/// </remarks>
/// <value>The importance.</value>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="value"/> is not a valid <see cref="MessageImportance"/>.
/// </exception>
public MessageImportance Importance {
get { return importance; }
set {
if (value == importance)
return;
switch (value) {
case MessageImportance.Normal:
case MessageImportance.High:
case MessageImportance.Low:
SetHeader ("Importance", value.ToString ().ToLowerInvariant ());
importance = value;
break;
default:
throw new ArgumentOutOfRangeException (nameof (value));
}
}
}
/// <summary>
/// Get or set the value of the Priority header.
/// </summary>
/// <remarks>
/// Gets or sets the value of the Priority header.
/// </remarks>
/// <value>The priority.</value>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="value"/> is not a valid <see cref="MessagePriority"/>.
/// </exception>
public MessagePriority Priority {
get { return priority; }
set {
if (value == priority)
return;
string rawValue;
switch (value) {
case MessagePriority.NonUrgent:
rawValue = "non-urgent";
break;
case MessagePriority.Normal:
rawValue = "normal";
break;
case MessagePriority.Urgent:
rawValue = "urgent";
break;
default:
throw new ArgumentOutOfRangeException (nameof (value));
}
SetHeader ("Priority", rawValue);
priority = value;
}
}
/// <summary>
/// Get or set the value of the X-Priority header.
/// </summary>
/// <remarks>
/// Gets or sets the value of the X-Priority header.
/// </remarks>
/// <value>The priority.</value>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="value"/> is not a valid <see cref="MessagePriority"/>.
/// </exception>
public XMessagePriority XPriority {
get { return xpriority; }
set {
if (value == xpriority)
return;
string rawValue;
switch (value) {
case XMessagePriority.Highest:
rawValue = "1 (Highest)";
break;
case XMessagePriority.High:
rawValue = "2 (High)";
break;
case XMessagePriority.Normal:
rawValue = "3 (Normal)";
break;
case XMessagePriority.Low:
rawValue = "4 (Low)";
break;
case XMessagePriority.Lowest:
rawValue = "5 (Lowest)";
break;
default:
throw new ArgumentOutOfRangeException (nameof (value));
}
SetHeader ("X-Priority", rawValue);
xpriority = value;
}
}
/// <summary>
/// Gets or sets the address in the Sender header.
/// </summary>
/// <remarks>
/// The sender may differ from the addresses in <see cref="From"/> if
/// the message was sent by someone on behalf of someone else.
/// </remarks>
/// <value>The address in the Sender header.</value>
public MailboxAddress Sender {
get { return sender; }
set {
if (value == sender)
return;
if (value == null) {
RemoveHeader (HeaderId.Sender);
sender = null;
return;
}
var options = FormatOptions.Default;
var builder = new StringBuilder (" ");
int len = "Sender: ".Length;
value.Encode (options, builder, ref len);
builder.Append (options.NewLine);
var raw = Encoding.UTF8.GetBytes (builder.ToString ());
ReplaceHeader (HeaderId.Sender, "Sender", raw);
sender = value;
}
}
/// <summary>
/// Gets or sets the address in the Resent-Sender header.
/// </summary>
/// <remarks>
/// The resent sender may differ from the addresses in <see cref="ResentFrom"/> if
/// the message was sent by someone on behalf of someone else.
/// </remarks>
/// <value>The address in the Resent-Sender header.</value>
public MailboxAddress ResentSender {
get { return resentSender; }
set {
if (value == resentSender)
return;
if (value == null) {
RemoveHeader (HeaderId.ResentSender);
resentSender = null;
return;
}
var options = FormatOptions.Default;
var builder = new StringBuilder (" ");
int len = "Resent-Sender: ".Length;
value.Encode (options, builder, ref len);
builder.Append (options.NewLine);
var raw = Encoding.UTF8.GetBytes (builder.ToString ());
ReplaceHeader (HeaderId.ResentSender, "Resent-Sender", raw);
resentSender = value;
}
}
/// <summary>
/// Gets the list of addresses in the From header.
/// </summary>
/// <remarks>
/// <para>The "From" header specifies the author(s) of the message.</para>
/// <para>If more than one <see cref="MailboxAddress"/> is added to the
/// list of "From" addresses, the <see cref="Sender"/> should be set to the
/// single <see cref="MailboxAddress"/> of the personal actually sending
/// the message.</para>
/// </remarks>
/// <value>The list of addresses in the From header.</value>
public InternetAddressList From {
get { return addresses["From"]; }
}
/// <summary>
/// Gets the list of addresses in the Resent-From header.
/// </summary>
/// <remarks>
/// <para>The "Resent-From" header specifies the author(s) of the messagebeing
/// resent.</para>
/// <para>If more than one <see cref="MailboxAddress"/> is added to the
/// list of "Resent-From" addresses, the <see cref="ResentSender"/> should
/// be set to the single <see cref="MailboxAddress"/> of the personal actually
/// sending the message.</para>
/// </remarks>
/// <value>The list of addresses in the Resent-From header.</value>
public InternetAddressList ResentFrom {
get { return addresses["Resent-From"]; }
}
/// <summary>
/// Gets the list of addresses in the Reply-To header.
/// </summary>
/// <remarks>
/// <para>When the list of addresses in the Reply-To header is not empty,
/// it contains the address(es) where the author(s) of the message prefer
/// that replies be sent.</para>
/// <para>When the list of addresses in the Reply-To header is empty,
/// replies should be sent to the mailbox(es) specified in the From
/// header.</para>
/// </remarks>
/// <value>The list of addresses in the Reply-To header.</value>
public InternetAddressList ReplyTo {
get { return addresses["Reply-To"]; }
}
/// <summary>
/// Gets the list of addresses in the Resent-Reply-To header.
/// </summary>
/// <remarks>
/// <para>When the list of addresses in the Resent-Reply-To header is not empty,
/// it contains the address(es) where the author(s) of the resent message prefer
/// that replies be sent.</para>
/// <para>When the list of addresses in the Resent-Reply-To header is empty,
/// replies should be sent to the mailbox(es) specified in the Resent-From
/// header.</para>
/// </remarks>
/// <value>The list of addresses in the Resent-Reply-To header.</value>
public InternetAddressList ResentReplyTo {
get { return addresses["Resent-Reply-To"]; }
}
/// <summary>
/// Gets the list of addresses in the To header.
/// </summary>
/// <remarks>
/// The addresses in the To header are the primary recipients of
/// the message.
/// </remarks>
/// <value>The list of addresses in the To header.</value>
public InternetAddressList To {
get { return addresses["To"]; }
}
/// <summary>
/// Gets the list of addresses in the Resent-To header.
/// </summary>
/// <remarks>
/// The addresses in the Resent-To header are the primary recipients of
/// the message.
/// </remarks>
/// <value>The list of addresses in the Resent-To header.</value>
public InternetAddressList ResentTo {
get { return addresses["Resent-To"]; }
}
/// <summary>
/// Gets the list of addresses in the Cc header.
/// </summary>
/// <remarks>
/// The addresses in the Cc header are secondary recipients of the message
/// and are usually not the individuals being directly addressed in the
/// content of the message.
/// </remarks>
/// <value>The list of addresses in the Cc header.</value>
public InternetAddressList Cc {
get { return addresses["Cc"]; }
}
/// <summary>
/// Gets the list of addresses in the Resent-Cc header.
/// </summary>
/// <remarks>
/// The addresses in the Resent-Cc header are secondary recipients of the message
/// and are usually not the individuals being directly addressed in the
/// content of the message.
/// </remarks>
/// <value>The list of addresses in the Resent-Cc header.</value>
public InternetAddressList ResentCc {
get { return addresses["Resent-Cc"]; }
}
/// <summary>
/// Gets the list of addresses in the Bcc header.
/// </summary>
/// <remarks>
/// Recipients in the Blind-Carpbon-Copy list will not be visible to
/// the other recipients of the message.
/// </remarks>
/// <value>The list of addresses in the Bcc header.</value>
public InternetAddressList Bcc {
get { return addresses["Bcc"]; }
}
/// <summary>
/// Gets the list of addresses in the Resent-Bcc header.
/// </summary>
/// <remarks>
/// Recipients in the Resent-Bcc list will not be visible to
/// the other recipients of the message.
/// </remarks>
/// <value>The list of addresses in the Resent-Bcc header.</value>
public InternetAddressList ResentBcc {
get { return addresses["Resent-Bcc"]; }
}
/// <summary>
/// Gets or sets the subject of the message.
/// </summary>
/// <remarks>
/// <para>The Subject is typically a short string denoting the topic of the message.</para>
/// <para>Replies will often use <c>"Re: "</c> followed by the Subject of the original message.</para>
/// </remarks>
/// <value>The subject of the message.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
public string Subject {
get { return Headers["Subject"]; }
set {
if (value == null)
throw new ArgumentNullException (nameof (value));
SetHeader ("Subject", value);
}
}
/// <summary>
/// Gets or sets the date of the message.
/// </summary>
/// <remarks>
/// If the date is not explicitly set before the message is written to a stream,
/// the date will default to the exact moment when it is written to said stream.
/// </remarks>
/// <value>The date of the message.</value>
public DateTimeOffset Date {
get { return date; }
set {
if (date == value)
return;
SetHeader ("Date", DateUtils.FormatDate (value));
date = value;
}
}
/// <summary>
/// Gets or sets the Resent-Date of the message.
/// </summary>
/// <remarks>
/// Gets or sets the Resent-Date of the message.
/// </remarks>
/// <value>The Resent-Date of the message.</value>
public DateTimeOffset ResentDate {
get { return resentDate; }
set {
if (resentDate == value)
return;
SetHeader ("Resent-Date", DateUtils.FormatDate (value));
resentDate = value;
}
}
/// <summary>
/// Gets or sets the list of references to other messages.
/// </summary>
/// <remarks>
/// The References header contains a chain of Message-Ids back to the
/// original message that started the thread.
/// </remarks>
/// <value>The references.</value>
public MessageIdList References {
get { return references; }
}
/// <summary>
/// Gets or sets the Message-Id that this message is in reply to.
/// </summary>
/// <remarks>
/// If the message is a reply to another message, it will typically
/// use the In-Reply-To header to specify the Message-Id of the
/// original message being replied to.
/// </remarks>
/// <value>The message id that this message is in reply to.</value>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is improperly formatted.
/// </exception>
public string InReplyTo {
get { return inreplyto; }
set {
if (inreplyto == value)
return;
if (value == null) {
RemoveHeader (HeaderId.InReplyTo);
inreplyto = null;
return;
}
var buffer = Encoding.UTF8.GetBytes (value);
MailboxAddress mailbox;
int index = 0;
if (!MailboxAddress.TryParse (Headers.Options, buffer, ref index, buffer.Length, false, out mailbox))
throw new ArgumentException ("Invalid Message-Id format.", nameof (value));
inreplyto = mailbox.Address;
SetHeader ("In-Reply-To", "<" + inreplyto + ">");
}
}
/// <summary>
/// Gets or sets the message identifier.
/// </summary>
/// <remarks>
/// <para>The Message-Id is meant to be a globally unique identifier for
/// a message.</para>
/// <para><see cref="MimeKit.Utils.MimeUtils.GenerateMessageId()"/> can be used
/// to generate this value.</para>
/// </remarks>
/// <value>The message identifier.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is improperly formatted.
/// </exception>
public string MessageId {
get { return messageId; }
set {
if (value == null)
throw new ArgumentNullException (nameof (value));
if (messageId == value)
return;
var buffer = Encoding.UTF8.GetBytes (value);
MailboxAddress mailbox;
int index = 0;
if (!MailboxAddress.TryParse (Headers.Options, buffer, ref index, buffer.Length, false, out mailbox))
throw new ArgumentException ("Invalid Message-Id format.", nameof (value));
messageId = mailbox.Address;
SetHeader ("Message-Id", "<" + messageId + ">");
}
}
/// <summary>
/// Gets or sets the Resent-Message-Id header.
/// </summary>
/// <remarks>
/// <para>The Resent-Message-Id is meant to be a globally unique identifier for
/// a message.</para>
/// <para><see cref="MimeKit.Utils.MimeUtils.GenerateMessageId()"/> can be used
/// to generate this value.</para>
/// </remarks>
/// <value>The Resent-Message-Id.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is improperly formatted.
/// </exception>
public string ResentMessageId {
get { return resentMessageId; }
set {
if (value == null)
throw new ArgumentNullException (nameof (value));
if (resentMessageId == value)
return;
var buffer = Encoding.UTF8.GetBytes (value);
MailboxAddress mailbox;
int index = 0;
if (!MailboxAddress.TryParse (Headers.Options, buffer, ref index, buffer.Length, false, out mailbox))
throw new ArgumentException ("Invalid Resent-Message-Id format.", nameof (value));
resentMessageId = mailbox.Address;
SetHeader ("Resent-Message-Id", "<" + resentMessageId + ">");
}
}
/// <summary>
/// Gets or sets the MIME-Version.
/// </summary>
/// <remarks>
/// The MIME-Version header specifies the version of the MIME specification
/// that the message was created for.
/// </remarks>
/// <value>The MIME version.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
public Version MimeVersion {
get { return version; }
set {
if (value == null)
throw new ArgumentNullException (nameof (value));
if (version != null && version.CompareTo (value) == 0)
return;
SetHeader ("MIME-Version", value.ToString ());
version = value;
}
}
/// <summary>
/// Gets or sets the body of the message.
/// </summary>
/// <remarks>
/// <para>The body of the message can either be plain text or it can be a
/// tree of MIME entities such as a text/plain MIME part and a collection
/// of file attachments.</para>
/// <para>For a convenient way of constructing message bodies, see the
/// <see cref="BodyBuilder"/> class.</para>
/// </remarks>
/// <value>The body of the message.</value>
public MimeEntity Body {
get; set;
}
static bool TryGetMultipartBody (Multipart multipart, TextFormat format, out string body)
{
var alternative = multipart as MultipartAlternative;
if (alternative != null) {
body = alternative.GetTextBody (format);
return body != null;
}
var related = multipart as MultipartRelated;
Multipart multi;
TextPart text;
if (related == null) {
// Note: This is probably a multipart/mixed... and if not, we can still treat it like it is.
for (int i = 0; i < multipart.Count; i++) {
multi = multipart[i] as Multipart;
// descend into nested multiparts, if there are any...
if (multi != null) {
if (TryGetMultipartBody (multi, format, out body))
return true;
// The text body should never come after a multipart.
break;
}
text = multipart[i] as TextPart;
// Look for the first non-attachment text part (realistically, the body text will
// preceed any attachments, but I'm not sure we can rely on that assumption).
if (text != null && !text.IsAttachment) {
if (text.IsFormat (format)) {
body = MultipartAlternative.GetText (text);
return true;
}
// Note: the first text/* part in a multipart/mixed is the text body.
// If it's not in the format we're looking for, then it doesn't exist.
break;
}
}
} else {
// Note: If the multipart/related root document is HTML, then this is the droid we are looking for.
var root = related.Root;
text = root as TextPart;
if (text != null) {
body = text.IsFormat (format) ? text.Text : null;
return body != null;
}
// maybe the root is another multipart (like multipart/alternative)?
multi = root as Multipart;
if (multi != null)
return TryGetMultipartBody (multi, format, out body);
}
body = null;
return false;
}
/// <summary>
/// Gets the text body of the message if it exists.
/// </summary>
/// <remarks>
/// <para>Gets the text content of the first text/plain body part that is found (in depth-first
/// search order) which is not an attachment.</para>
/// </remarks>
/// <value>The text body if it exists; otherwise, <c>null</c>.</value>
public string TextBody {
get { return GetTextBody (TextFormat.Plain); }
}
/// <summary>
/// Gets the html body of the message if it exists.
/// </summary>
/// <remarks>
/// <para>Gets the HTML-formatted body of the message if it exists.</para>
/// </remarks>
/// <value>The html body if it exists; otherwise, <c>null</c>.</value>
public string HtmlBody {
get { return GetTextBody (TextFormat.Html); }
}
/// <summary>
/// Gets the text body in the specified format.
/// </summary>
/// <remarks>
/// Gets the text body in the specified format, if it exists.
/// </remarks>
/// <returns>The text body in the desired format if it exists; otherwise, <c>null</c>.</returns>
/// <param name="format">The desired text format.</param>
public string GetTextBody (TextFormat format)
{
var multipart = Body as Multipart;
if (multipart != null) {
string text;
if (TryGetMultipartBody (multipart, format, out text))
return text;
} else {
var body = Body as TextPart;
if (body != null && body.IsFormat (format) && !body.IsAttachment)
return body.Text;
}
return null;
}
static IEnumerable<MimeEntity> EnumerateMimeParts (MimeEntity entity)
{
if (entity == null)
yield break;
var multipart = entity as Multipart;
if (multipart != null) {
foreach (var subpart in multipart) {
foreach (var part in EnumerateMimeParts (subpart))
yield return part;
}
yield break;
}
yield return entity;
}
/// <summary>
/// Gets the body parts of the message.
/// </summary>
/// <remarks>
/// Traverses over the MIME tree, enumerating all of the <see cref="MimeEntity"/> objects,
/// but does not traverse into the bodies of attached messages.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\AttachmentExamples.cs" region="SaveBodyParts" />
/// </example>
/// <value>The body parts.</value>
public IEnumerable<MimeEntity> BodyParts {
get { return EnumerateMimeParts (Body); }
}
/// <summary>
/// Gets the attachments.
/// </summary>
/// <remarks>
/// Traverses over the MIME tree, enumerating all of the <see cref="MimeEntity"/> objects that
/// have a Content-Disposition header set to <c>"attachment"</c>.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\AttachmentExamples.cs" region="SaveAttachments" />
/// </example>
/// <value>The attachments.</value>
public IEnumerable<MimeEntity> Attachments {
get { return EnumerateMimeParts (Body).Where (x => x.IsAttachment); }
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="MimeKit.MimeMessage"/>.
/// </summary>
/// <remarks>
/// <para>Returns a <see cref="System.String"/> that represents the current <see cref="MimeKit.MimeMessage"/>.</para>
/// <para><alert class="warning">Note: In general, the string returned from this method SHOULD NOT be used for serializing
/// the message to disk. It is recommended that you use <see cref="WriteTo(Stream,CancellationToken)"/> instead.</alert></para>
/// </remarks>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="MimeKit.MimeMessage"/>.</returns>
public override string ToString ()
{
using (var memory = new MemoryStream ()) {
WriteTo (FormatOptions.Default, memory);
#if !PORTABLE && !NETSTANDARD
var buffer = memory.GetBuffer ();
#else
var buffer = memory.ToArray ();
#endif
int count = (int) memory.Length;