forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageBuilder.cs
461 lines (445 loc) · 17.6 KB
/
MessageBuilder.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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
namespace S22.Imap {
/// <summary>
/// A helper class for reading mail message data and building a MailMessage
/// instance out of it.
/// </summary>
internal static class MessageBuilder {
/// <summary>
/// Creates a new empty instance of the MailMessage class from a string
/// containing a raw mail message header.
/// </summary>
/// <param name="text">A string containing the mail header to create
/// the MailMessage instance from.</param>
/// <returns>A MailMessage instance with initialized Header fields but
/// no content</returns>
internal static MailMessage FromHeader(string text) {
NameValueCollection header = ParseMailHeader(text);
MailMessage m = new MailMessage();
foreach (string key in header) {
string value = header.GetValues(key)[0];
try {
m.Headers.Add(key, value);
} catch {
// HeaderCollection throws an exception if adding an empty string as
// value, which can happen, if reading a mail message with an empty
// subject.
// Also spammers often forge headers, so just fall through and ignore.
}
}
Match ma = Regex.Match(header["Subject"] ?? "", @"=\?([A-Za-z0-9\-_]+)");
if (ma.Success) {
// encoded-word subject. A subject must not contain any encoded newline
// characters, so if we find any, we strip them off.
m.SubjectEncoding = Util.GetEncoding(ma.Groups[1].Value);
try {
m.Subject = Util.DecodeWords(header["Subject"]).
Replace("\n", "").Replace("\r", "");
} catch {
// If, for any reason, decoding fails, set the subject to the
// original, unaltered string.
m.Subject = header["Subject"];
}
} else {
m.SubjectEncoding = Encoding.ASCII;
m.Subject = header["Subject"];
}
m.Priority = ParsePriority(header["Priority"]);
SetAddressFields(m, header);
return m;
}
/// <summary>
/// Creates a new instance of the MailMessage class from a string
/// containing raw RFC822/MIME mail message data.
/// </summary>
/// <param name="text">A string containing the mail message data to
/// create the MailMessage instance from.</param>
/// <returns>An initialized instance of the MailMessage class.</returns>
/// <remarks>This is used when fetching entire messages instead
/// of the partial-fetch mechanism because it saves redundant
/// round-trips to the server.</remarks>
internal static MailMessage FromMIME822(string text) {
StringReader reader = new StringReader(text);
StringBuilder header = new StringBuilder();
string line;
while(!String.IsNullOrEmpty(line = reader.ReadLine()))
header.AppendLine(line);
MailMessage m = FromHeader(header.ToString());
MIMEPart[] parts = ParseMailBody(reader.ReadToEnd(), m.Headers);
foreach (MIMEPart p in parts)
m.AddBodypart(BodypartFromMIME(p), p.body);
return m;
}
/// <summary>
/// Parses the mail header of a mail message and returns it as a
/// NameValueCollection.
/// </summary>
/// <param name="header">The mail header to parse.</param>
/// <returns>A NameValueCollection containing the header fields as keys
/// with their respective values as values.</returns>
internal static NameValueCollection ParseMailHeader(string header) {
StringReader reader = new StringReader(header);
NameValueCollection coll = new NameValueCollection();
string line, fieldname = null, fieldvalue = null;
while ((line = reader.ReadLine()) != null) {
if (line == String.Empty)
continue;
// Values may stretch over several lines.
if (line[0] == ' ' || line[0] == '\t') {
if(fieldname != null)
coll[fieldname] = coll[fieldname] + line.TrimEnd();
continue;
}
// The mail header consists of field:value pairs.
int delimiter = line.IndexOf(':');
if (delimiter < 0)
continue;
fieldname = line.Substring(0, delimiter).Trim();
fieldvalue = line.Substring(delimiter + 1).Trim();
coll.Add(fieldname, fieldvalue);
}
return coll;
}
/// <summary>
/// Parses a MIME header field which can contain multiple 'parameter = value'
/// pairs (such as Content-Type: text/html; charset=iso-8859-1).
/// </summary>
/// <param name="field">The header field to parse</param>
/// <returns>A NameValueCollection containing the parameter names as keys
/// with the respective parameter values as values.</returns>
/// <remarks>The value of the actual field disregarding the 'parameter = value'
/// pairs is stored in the collection under the key "value" (in the above example
/// of Content-Type, this would be "text/html").</remarks>
private static NameValueCollection ParseMIMEField(string field) {
NameValueCollection coll = new NameValueCollection();
try {
MatchCollection matches = Regex.Matches(field,
"([\\w\\-]+)\\s*=\\s*([^;]+)");
foreach (Match m in matches)
coll.Add(m.Groups[1].Value, m.Groups[2].Value.Trim('"'));
Match mvalue = Regex.Match(field, @"^\s*([^;]+)");
coll.Add("value", mvalue.Success ? mvalue.Groups[1].Value.Trim() : "");
} catch {
// We don't want this to blow up on the user with weird mails so
// just return an empty collection.
coll.Add("value", String.Empty);
}
return coll;
}
/// <summary>
/// Parses a mail header address-list field such as To, Cc and Bcc which
/// can contain multiple email addresses.
/// </summary>
/// <param name="list">The address-list field to parse</param>
/// <returns>An array of MailAddress objects representing the parsed
/// mail addresses.</returns>
internal static MailAddress[] ParseAddressList(string list) {
List<MailAddress> mails = new List<MailAddress>();
try {
MailAddressCollection mcol = new MailAddressCollection();
// Use .NET internal MailAddressParser.ParseMultipleAddresses
// to parse the address list.
mcol.Add(list);
foreach (MailAddress m in mcol) {
// We might still need to decode the display name if it is
// q-encoded.
string displayName = Util.DecodeWord(m.DisplayName);
mails.Add(new MailAddress(m.Address, displayName));
}
} catch {
// We don't want this to throw any exceptions even if the
// address list is malformed.
}
return mails.ToArray();
}
/// <summary>
/// Parses a mail message identifier from a string.
/// </summary>
/// <param name="field">The field to parse the message id from</param>
/// <exception cref="ArgumentException">Thrown when the field
/// argument does not contain a valid message identifier.</exception>
/// <returns>The parsed message id</returns>
/// <remarks>A message identifier (msg-id) is a globally unique
/// identifier for a message.</remarks>
private static string ParseMessageId(string field) {
// A msg-id is enclosed in < > brackets.
Match m = Regex.Match(field, @"<(.+)>");
if (m.Success)
return m.Groups[1].Value;
throw new ArgumentException("The field does not contain a valid message " +
"identifier: " + field);
}
/// <summary>
/// Parses the priority of a mail message which can be specified
/// as part of the header information.
/// </summary>
/// <param name="priority">The mail header priority value. The value
/// can be null in which case a "normal priority" is returned.</param>
/// <returns>A value from the MailPriority enumeration corresponding to
/// the specified mail priority. If the passed priority value is null
/// or invalid, a normal priority is assumed and MailPriority.Normal
/// is returned.</returns>
private static MailPriority ParsePriority(string priority) {
Dictionary<string, MailPriority> Map =
new Dictionary<string, MailPriority>(StringComparer.OrdinalIgnoreCase) {
{ "non-urgent", MailPriority.Low },
{ "normal", MailPriority.Normal },
{ "urgent", MailPriority.High }
};
try {
return Map[priority];
} catch {
return MailPriority.Normal;
}
}
/// <summary>
/// Sets the address fields (From, To, CC, etc.) of a MailMessage
/// object using the specified mail message header information.
/// </summary>
/// <param name="m">The MailMessage instance to operate on</param>
/// <param name="header">A collection of mail and MIME headers</param>
private static void SetAddressFields(MailMessage m, NameValueCollection header) {
MailAddress[] addr;
if (header["To"] != null) {
addr = ParseAddressList(header["To"]);
foreach (MailAddress a in addr)
m.To.Add(a);
}
if (header["Cc"] != null) {
addr = ParseAddressList(header["Cc"]);
foreach (MailAddress a in addr)
m.CC.Add(a);
}
if (header["Bcc"] != null) {
addr = ParseAddressList(header["Bcc"]);
foreach (MailAddress a in addr)
m.Bcc.Add(a);
}
if (header["From"] != null) {
addr = ParseAddressList(header["From"]);
if(addr.Length > 0)
m.From = addr[0];
}
if (header["Sender"] != null) {
addr = ParseAddressList(header["Sender"]);
if(addr.Length > 0)
m.Sender = addr[0];
}
if (header["Reply-to"] != null) {
addr = ParseAddressList(header["Reply-to"]);
foreach (MailAddress a in addr)
m.ReplyToList.Add(a);
}
}
/// <summary>
/// Adds a body part to an existing MailMessage instance.
/// </summary>
/// <param name="message">Extension method for the MailMessage class.</param>
/// <param name="part">The body part to add to the MailMessage instance.</param>
/// <param name="content">The content of the body part.</param>
internal static void AddBodypart(this MailMessage message, Bodypart part, string content) {
Encoding encoding = part.Parameters.ContainsKey("Charset") ?
Util.GetEncoding(part.Parameters["Charset"]) : Encoding.ASCII;
// Decode the content if it is encoded.
byte[] bytes;
try {
switch (part.Encoding) {
case ContentTransferEncoding.QuotedPrintable:
bytes = encoding.GetBytes(Util.QPDecode(content, encoding));
break;
case ContentTransferEncoding.Base64:
bytes = Util.Base64Decode(content);
break;
default:
bytes = Encoding.ASCII.GetBytes(content);
break;
}
} catch {
// If it's not a valid Base64 or quoted-printable encoded string
// just leave the data as is
bytes = Encoding.ASCII.GetBytes(content);
}
// If the MailMessage's Body fields haven't been initialized yet, put it there.
// Some weird (i.e. spam) mails like to omit content-types so we don't check for
// that here and just assume it's text.
if (String.IsNullOrEmpty(message.Body) &&
part.Disposition.Type != ContentDispositionType.Attachment) {
message.Body = encoding.GetString(bytes);
message.BodyEncoding = encoding;
message.IsBodyHtml = part.Subtype.ToLower() == "html";
return;
}
if (part.Disposition.Type == ContentDispositionType.Attachment)
message.Attachments.Add(CreateAttachment(part, bytes));
else
message.AlternateViews.Add(CreateAlternateView(part, bytes));
}
/// <summary>
/// Creates an instance of the Attachment class used by the MailMessage class
/// to store mail message attachments.
/// </summary>
/// <param name="part">The MIME body part to create the attachment from.</param>
/// <param name="bytes">An array of bytes composing the content of the
/// attachment</param>
/// <returns>An initialized instance of the Attachment class</returns>
private static Attachment CreateAttachment(Bodypart part, byte[] bytes) {
MemoryStream stream = new MemoryStream(bytes);
string name = part.Disposition.Filename;
// Many MUAs put the file name in the name parameter of the content-type
// header instead of the filename parameter of the content-disposition
// header.
if (String.IsNullOrEmpty(name) && part.Parameters.ContainsKey("name"))
name = part.Parameters["name"];
if (String.IsNullOrEmpty(name))
name = Path.GetRandomFileName();
Attachment attachment = new Attachment(stream, name);
try {
attachment.ContentId = ParseMessageId(part.Id);
} catch {}
try {
attachment.ContentType = new System.Net.Mime.ContentType(
part.Type.ToString().ToLower() + "/" + part.Subtype.ToLower());
} catch {
attachment.ContentType = new System.Net.Mime.ContentType();
}
// Workaround: filename from Attachment constructor is ignored with Mono.
attachment.Name = name;
attachment.ContentDisposition.FileName = name;
return attachment;
}
/// <summary>
/// Creates an instance of the AlternateView class used by the MailMessage class
/// to store alternate views of the mail message's content.
/// </summary>
/// <param name="part">The MIME body part to create the alternate view from.</param>
/// <param name="bytes">An array of bytes composing the content of the
/// alternate view</param>
/// <returns>An initialized instance of the AlternateView class</returns>
private static AlternateView CreateAlternateView(Bodypart part, byte[] bytes) {
MemoryStream stream = new MemoryStream(bytes);
System.Net.Mime.ContentType contentType;
try {
contentType = new System.Net.Mime.ContentType(
part.Type.ToString().ToLower() + "/" + part.Subtype.ToLower());
} catch {
contentType = new System.Net.Mime.ContentType();
}
AlternateView view = new AlternateView(stream, contentType);
try {
view.ContentId = ParseMessageId(part.Id);
} catch {}
return view;
}
/// <summary>
/// Parses the body part of a MIME/RFC822 mail message.
/// </summary>
/// <param name="body">The body of the mail message.</param>
/// <param name="header">The header of the mail message whose body
/// will be parsed.</param>
/// <returns>An array of initialized MIMEPart instances representing
/// the body parts of the mail message.</returns>
private static MIMEPart[] ParseMailBody(string body,
NameValueCollection header) {
NameValueCollection contentType = ParseMIMEField(header["Content-Type"]);
if (contentType["Boundary"] != null) {
return ParseMIMEParts(new StringReader(body), contentType["Boundary"]);
} else {
return new MIMEPart[] {
new MIMEPart() { body = body,
header = new NameValueCollection() {
{ "Content-Type", header["Content-Type"] },
{ "Content-Id", header["Content-Id"] },
{ "Content-Transfer-Encoding", header["Content-Transfer-Encoding"] },
{ "Content-Disposition", header["Content-Disposition"] }
}
}
};
}
}
/// <summary>
/// Parses the body of a multipart MIME mail message.
/// </summary>
/// <param name="reader">An instance of the StringReader class initialized
/// with a string containing the body of the mail message.</param>
/// <param name="boundary">The boundary value as is present as part of
/// the Content-Type header field in multipart mail messages.</param>
/// <returns>An array of initialized MIMEPart instances representing
/// the various parts of the MIME mail message.</returns>
private static MIMEPart[] ParseMIMEParts(StringReader reader, string boundary) {
List<MIMEPart> list = new List<MIMEPart>();
string start = "--" + boundary, end = "--" + boundary + "--", line;
// Skip everything up to the first boundary.
while ((line = reader.ReadLine()) != null) {
if (line.StartsWith(start))
break;
}
// Read the MIME parts which are delimited by boundary strings.
while (line != null && line.StartsWith(start)) {
MIMEPart p = new MIMEPart();
// Read the part header.
StringBuilder header = new StringBuilder();
while (!String.IsNullOrEmpty(line = reader.ReadLine()))
header.AppendLine(line);
p.header = ParseMailHeader(header.ToString());
// Account for nested multipart content.
NameValueCollection contentType = ParseMIMEField(p.header["Content-Type"]);
if (contentType["Boundary"] != null)
list.AddRange(ParseMIMEParts(reader, contentType["boundary"]));
// Read the part body.
StringBuilder body = new StringBuilder();
while ((line = reader.ReadLine()) != null) {
if (line.StartsWith(start))
break;
body.AppendLine(line);
}
p.body = body.ToString();
// Add the MIME part to the list unless body is null or empty which means
// the body contained nested multipart content.
if (!String.IsNullOrWhiteSpace(p.body))
list.Add(p);
// If this boundary is actually the end boundary, we're done.
if (line == null || line.StartsWith(end))
break;
}
return list.ToArray();
}
/// <summary>
/// Glue method to create a bodypart from a MIMEPart instance.
/// </summary>
/// <param name="mimePart">The MIMEPart instance to create the
/// bodypart instance from.</param>
/// <returns>An initialized instance of the Bodypart class.</returns>
private static Bodypart BodypartFromMIME(MIMEPart mimePart) {
NameValueCollection contentType = ParseMIMEField(
mimePart.header["Content-Type"]);
Bodypart p = new Bodypart(null);
Match m = Regex.Match(contentType["value"], "(.+)/(.+)");
if (m.Success) {
p.Type = ContentTypeMap.fromString(m.Groups[1].Value);
p.Subtype = m.Groups[2].Value;
}
p.Encoding = ContentTransferEncodingMap.fromString(
mimePart.header["Content-Transfer-Encoding"]);
p.Id = mimePart.header["Content-Id"];
foreach (string k in contentType.AllKeys)
p.Parameters.Add(k, contentType[k]);
p.Size = mimePart.body.Length;
if (mimePart.header["Content-Disposition"] != null) {
NameValueCollection disposition = ParseMIMEField(
mimePart.header["Content-Disposition"]);
p.Disposition.Type = ContentDispositionTypeMap.fromString(
disposition["value"]);
p.Disposition.Filename = disposition["Filename"];
foreach (string k in disposition.AllKeys)
p.Disposition.Attributes.Add(k, disposition[k]);
}
return p;
}
}
}