forked from smiley22/S22.Imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MailMessage.cs
373 lines (357 loc) · 15.2 KB
/
MailMessage.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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
namespace S22.Imap {
/// <summary>
/// Adds extension methods to the MailMessage class of the .NET Framework.
/// </summary>
/// <remarks>
/// Most of the methods are only used internally and are not visible outside of the
/// S22.Imap assembly.
/// </remarks>
public static class MailMessageExtension {
/// <summary>
/// Returns the date and time the mail message was composed.
/// </summary>
/// <param name="message">The MailMessage instance to return the date and time for.</param>
/// <returns>The date and time the mail message was composed, or null if the mail message
/// does not contain any date information.</returns>
public static DateTime? Date(this MailMessage message) {
string date = message.Headers["Date"];
if (String.IsNullOrEmpty(date))
return null;
// Dates are sometimes suffixed with comments indicating the timezone, for example:
// Tue, 29 Mar 2005 15:11:45 -0800 (PST).
date = Regex.Replace(date, @"\([^\)]+\)", String.Empty);
try {
return DateTime.Parse(date);
} catch (FormatException) {
return null;
}
}
/// <summary>
/// Constructs a textual representation of a mail message from the specified MailMessage
/// instance compliant with the RFC822 and MIME standards.
/// </summary>
/// <param name="message">The MailMessage instance to construct the textual representation
/// from.</param>
/// <returns>An RFC822/MIME-compliant string representing the specified mail message.</returns>
/// <exception cref="InvalidOperationException">The From property is null or has not been
/// properly initialized.</exception>
internal static string ToMIME822(this MailMessage message) {
NameValueCollection header = BuildHeader(message);
StringBuilder builder = new StringBuilder();
foreach (string h in header) {
string line = h + ": " + header[h];
// RFC2822 states a line should at max be 78 characters (excluding CRLF)
// so long headers may span over several lines.
/*
string[] chunks = line.ToChunks(70);
builder.AppendLine(chunks[0]);
for (int i = 1; i < chunks.Length; i++)
builder.AppendLine(" " + chunks[i]);
*/
builder.AppendLine(line);
}
// The mail body is separated by an empty line from the header.
builder.AppendLine();
builder.Append(BuildBody(message, header));
builder.AppendLine();
return builder.ToString();
}
/// <summary>
/// Builds a RFC822/MIME-compliant mail header from the specified MailMessage instance and
/// returns it as a NameValueCollection.
/// </summary>
/// <param name="m">The MailMessage instance to build the header from.</param>
/// <returns>A NameValueCollection representing the RFC822/MIME mail header fields.</returns>
static NameValueCollection BuildHeader(MailMessage m) {
string[] ignore = new string[] {
"MIME-Version", "Date", "Subject", "From", "To", "Cc", "Bcc",
"Content-Type", "Content-Transfer-Encoding", "Priority",
"Reply-To", "X-Priority", "Importance", "Sender", "Message-Id"
};
var date = String.IsNullOrEmpty(m.Headers["Date"]) ? DateTime.Now.ToString("R") :
m.Headers["Date"];
NameValueCollection header = new NameValueCollection() {
{ "MIME-Version", "1.0" },
{ "Date", date },
{ "Priority", PriorityMap[m.Priority] },
{ "Importance", ImportanceMap[m.Priority] }
};
if (m.From == null)
throw new InvalidOperationException("The From property must not be null.");
header.Add("From", m.From.To822Address());
if (m.Subject != null)
header.Add("Subject", m.Subject.IsASCII() ? m.Subject : Base64Encode(m.Subject));
foreach (MailAddress a in m.To)
header.Add("To", a.To822Address());
foreach (MailAddress a in m.CC)
header.Add("Cc", a.To822Address());
foreach (MailAddress a in m.Bcc)
header.Add("Bcc", a.To822Address());
bool multipart = m.AlternateViews.Count > 0 || m.Attachments.Count > 0;
if (!multipart) {
string contentType = m.IsBodyHtml ? "text/html" : "text/plain";
if (m.BodyEncoding != null)
contentType = contentType + "; charset=" + m.BodyEncoding.WebName;
header.Add("Content-Type", contentType);
if (m.Body != null && !m.Body.IsASCII())
header.Add("Content-Transfer-Encoding", "base64");
} else {
string contentType = (m.Attachments.Count == 0 ?
"multipart/alternative" : "multipart/mixed") + "; boundary=" +
GenerateContentBoundary();
header.Add("Content-Type", contentType);
}
// Add any custom headers added by the user.
foreach (string key in m.Headers) {
if (ignore.Contains(key, StringComparer.OrdinalIgnoreCase))
continue;
header.Add(key, m.Headers.GetValues(key)[0]);
}
return header;
}
/// <summary>
/// A map for mapping the values of the MailPriority enumeration to their corresponding MIME
/// priority values as defined in RFC2156.
/// </summary>
static Dictionary<MailPriority, string> PriorityMap =
new Dictionary<MailPriority, string>() {
{ MailPriority.Low, "non-urgent" },
{ MailPriority.Normal, "normal" },
{ MailPriority.High, "urgent" }
};
/// <summary>
/// A map for mapping the values of the MailPriority enumeration to their corresponding MIME
/// importance values as defined in RFC2156.
/// </summary>
static Dictionary<MailPriority, string> ImportanceMap =
new Dictionary<MailPriority, string>() {
{ MailPriority.Low, "low" },
{ MailPriority.Normal, "normal" },
{ MailPriority.High, "high" }
};
/// <summary>
/// Takes a unicode string and encodes it using Q-encoding.
/// </summary>
/// <param name="s">The string to encode.</param>
/// <returns>The input string encoded as Q-encoded string containing only ASCII
/// characters.</returns>
static string QEncode(string s) {
StringBuilder builder = new StringBuilder("=?UTF-8?Q?");
char[] chars = Encoding.Unicode.GetChars(Encoding.Unicode.GetBytes(s));
foreach (char c in chars) {
if (c < 32 || c == '=' || c == '_' || c == '?' || c > 126)
builder.Append(string.Format("={0:X2}", (int)c));
else if (c == ' ')
builder.Append('_');
else
builder.Append(c);
}
return builder.ToString() + "?=";
}
/// <summary>
/// Takes a unicode string and encodes it using Base64-encoding.
/// </summary>
/// <param name="s">The string to encode.</param>
/// <returns>The input string encoded as Base64-encoded string containing only ASCII
/// characters.</returns>
static string Base64Encode(string s) {
StringBuilder builder = new StringBuilder("=?UTF-8?B?");
string b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
return builder.Append(b64).ToString() + "?=";
}
/// <summary>
/// Creates an address string from the specified MailAddress instance in compliance with the
/// address specification as outlined in RFC2822 under section 3.4
/// </summary>
/// <param name="address">The MailAddress instance to create the address string from.</param>
/// <returns>An address string as is used in RFC822 mail headers.</returns>
internal static string To822Address(this MailAddress address) {
if (!String.IsNullOrEmpty(address.DisplayName)) {
string name = address.DisplayName.IsASCII() ?
String.Format("\"{0}\"", address.DisplayName) : Base64Encode(address.DisplayName);
return name + " <" + address.Address + ">";
}
return address.Address;
}
/// <summary>
/// Generates a unique sequence of characters for indicating a boundary between parts in a
/// multipart message.
/// </summary>
/// <returns>A unique content boundary string.</returns>
static string GenerateContentBoundary() {
return Guid.NewGuid().ToString("N");
}
/// <summary>
/// Builds an RFC822/MIME-compliant mail body from the specified MailMessage instance and
/// returns it as a formatted string.
/// </summary>
/// <param name="m">The MailMessage instance to build the mail body from.</param>
/// <param name="header">The RFC822/MIME mail header to use for constructing the mail
/// body.</param>
/// <returns>An RFC822/MIME-compliant mail body as a string.</returns>
/// <remarks>According to RFC2822 each line of a mail message should at max be 78 characters in
/// length excluding carriage return and newline characters. This method accounts for that and
/// ensures line breaks are inserted to meet this requirement.</remarks>
static string BuildBody(MailMessage m, NameValueCollection header) {
StringBuilder builder = new StringBuilder();
bool multipart = header["Content-Type"].Contains("boundary");
// Just a regular RFC822 mail w/o any MIME parts.
if (!multipart) {
AddBody(builder, m, header);
return builder.ToString();
}
Match match = Regex.Match(header["Content-Type"], @"boundary=(\w+)");
string boundary = match.Groups[1].Value;
// Add the start boundary.
builder.AppendLine("--" + boundary);
bool nestParts = m.AlternateViews.Count > 0 && m.Attachments.Count > 0;
if (nestParts) {
AddNestedAlternative(builder, m, header);
builder.AppendLine("--" + boundary);
AddNestedMixed(builder, m);
} else {
AddBody(builder, m, header, true);
foreach (AlternateView v in m.AlternateViews) {
builder.AppendLine("--" + boundary);
AddAttachment(builder, v);
}
foreach (Attachment a in m.Attachments) {
builder.AppendLine("--" + boundary);
AddAttachment(builder, a);
}
}
// Add the end boundary.
builder.AppendLine("--" + boundary + "--");
return builder.ToString();
}
/// <summary>
/// Adds a body part to the specified Stringbuilder object composed from the Body and
/// BodyEncoding properties of the MailMessage class.
/// </summary>
/// <param name="builder">The Stringbuilder to append the body part to.</param>
/// <param name="m">The MailMessage instance to build the body part from.</param>
/// <param name="header">The RFC822/MIME mail header to use for constructing the mail body.</param>
/// <param name="addHeaders">Set to true to append body headers before adding the actual body
/// part content.</param>
static void AddBody(StringBuilder builder, MailMessage m,
NameValueCollection header, bool addHeaders = false) {
bool base64 = header["Content-Transfer-Encoding"] == "base64";
if (addHeaders) {
string contentType = m.IsBodyHtml ? "text/html" : "text/plain";
if (m.BodyEncoding != null)
contentType = contentType + "; charset=" + m.BodyEncoding.WebName;
builder.AppendLine("Content-Type: " + contentType);
if (m.Body != null && !m.Body.IsASCII()) {
builder.AppendLine("Content-Transfer-Encoding: base64");
base64 = true;
}
builder.AppendLine();
}
string body = m.Body;
if (base64) {
byte[] bytes = m.BodyEncoding.GetBytes(m.Body);
body = Convert.ToBase64String(bytes);
}
StringReader reader = new StringReader(body);
char[] line = new char[76];
int read;
while ((read = reader.Read(line, 0, line.Length)) > 0)
builder.AppendLine(new string(line, 0, read));
}
/// <summary>
/// Creates a MIME body part from an entry of the AlternateView or Attachments collection of a
/// MailMessage instance and appends it to the specified Stringbuilder instance.
/// </summary>
/// <param name="builder">The Stringbuilder instance to append the body part to.</param>
/// <param name="view">An entry from either the AlternateView or the Attachments collection of
/// a MailMessage instance.</param>
static void AddAttachment(StringBuilder builder, AttachmentBase view) {
// Append the MIME headers for this body part.
string contentType = "Content-Type: " + view.ContentType.MediaType;
foreach (string key in view.ContentType.Parameters.Keys) {
contentType = contentType + "; " + key + "=" +
view.ContentType.Parameters[key];
}
builder.AppendLine(contentType);
builder.AppendLine("Content-Transfer-Encoding: base64");
if (!String.IsNullOrEmpty(view.ContentId))
builder.AppendLine("Content-Id: <" + view.ContentId + ">");
if (view is Attachment)
builder.AppendLine("Content-Disposition: attachment");
builder.AppendLine();
// Append the actual body part contents encoded as Base64.
using (MemoryStream memstream = new MemoryStream()) {
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead =
view.ContentStream.Read(buffer, 0, buffer.Length)) > 0) {
memstream.Write(buffer, 0, bytesRead);
}
string str = Convert.ToBase64String(memstream.ToArray());
StringReader reader = new StringReader(str);
char[] line = new char[76];
int read;
while ((read = reader.Read(line, 0, line.Length)) > 0)
builder.AppendLine(new string(line, 0, read));
}
// Rewind the stream if it supports seeking.
if (view.ContentStream.CanSeek)
view.ContentStream.Seek(0, SeekOrigin.Begin);
}
/// <summary>
/// Creates a nested multipart/alternative part which contains all entries from the
/// AlternateViews collection of the specified MailMessage instance as well as the body part
/// for the Body and BodyEncoding properties of the specified MailMessage instance.
/// </summary>
/// <param name="builder">The StringBuilder instance to append to.</param>
/// <param name="m">The MailMessage instance whose AlternateView collection will be added to the
/// nested multipart/alternative part.</param>
/// <param name="header">The RFC822/MIME mail header to use for constructing the mail body.</param>
/// <remarks>This is used if the MailMessage instance contains both alternative views and
/// attachments. In this case the created RFC822/MIME mail message will contain nested body
/// parts.</remarks>
static void AddNestedAlternative(StringBuilder builder, MailMessage m,
NameValueCollection header) {
string boundary = GenerateContentBoundary();
builder.AppendLine("Content-Type: multipart/alternative; boundary=" + boundary);
builder.AppendLine();
// Add the body parts to the nested multipart/alternative part.
builder.AppendLine("--" + boundary);
AddBody(builder, m, header, true);
foreach (AlternateView v in m.AlternateViews) {
builder.AppendLine("--" + boundary);
AddAttachment(builder, v);
}
builder.AppendLine("--" + boundary + "--");
}
/// <summary>
/// Creates a nested multipart/mixed part which contains all entries from the Attachments
/// collection of the specified MailMessage instance.
/// </summary>
/// <param name="builder">The StringBuilder instance to append to.</param>
/// <param name="m">The MailMessage instance whose Attachments collection will be added to the
/// nested multipart/mixed part.</param>
/// <remarks>This is used if the MailMessage instance contains both alternative views and
/// attachments. In this case the created RFC822/MIME mail message will contain nested body
/// parts.</remarks>
static void AddNestedMixed(StringBuilder builder, MailMessage m) {
string boundary = GenerateContentBoundary();
builder.AppendLine("Content-Type: multipart/mixed; boundary=" + boundary);
builder.AppendLine();
// Add the body parts to the nested multipart/mixed part.
foreach (Attachment a in m.Attachments) {
builder.AppendLine("--" + boundary);
AddAttachment(builder, a);
}
builder.AppendLine("--" + boundary + "--");
}
}
}