summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Helpers/WebMail.cs
blob: 82c36065063042ec809dba8666c1e926baeacfdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web.Helpers.Resources;
using System.Web.WebPages.Scope;
using Microsoft.Internal.Web.Utils;

namespace System.Web.Helpers
{
    [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "WebMail", Justification = "The name of this class is consistent with the naming convention followed in other helpers")]
    public static class WebMail
    {
        internal static readonly object SmtpServerKey = new object();
        internal static readonly object SmtpPortKey = new object();
        internal static readonly object SmtpUseDefaultCredentialsKey = new object();
        internal static readonly object EnableSslKey = new object();
        internal static readonly object PasswordKey = new object();
        internal static readonly object UserNameKey = new object();
        internal static readonly object FromKey = new object();
        internal static readonly Lazy<IDictionary<object, object>> SmtpDefaults = new Lazy<IDictionary<object, object>>(ReadSmtpDefaults);

        /// <summary>
        /// MailMessage dictates that headers values that have equivalent properties would be discarded or overwritten. The list of values is available at 
        /// http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx
        /// </summary>
        private static readonly Dictionary<string, Action<MailMessage, string>> _actionableHeaders = new Dictionary<string, Action<MailMessage, string>>(StringComparer.OrdinalIgnoreCase)
        {
            { "Bcc", (message, value) => message.Bcc.Add(value) },
            { "Cc", (message, value) => message.CC.Add(value) },
            { "From", (mailMessage, value) =>
            {
                mailMessage.From = new MailAddress(value);
            }
                },
            { "Priority", SetPriority },
            { "Reply-To", (mailMessage, value) =>
            {
                mailMessage.ReplyToList.Add(value);
            }
                },
            { "Sender", (mailMessage, value) =>
            {
                mailMessage.Sender = new MailAddress(value);
            }
                },
            { "To", (mailMessage, value) =>
            {
                mailMessage.To.Add(value);
            }
                },
        };

        ///////////////////////////////////////////////////////////////////////////
        // Public Properties
        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "SmtpServer is more descriptive as compared to the actual argument \"value\"")]
        public static string SmtpServer
        {
            get { return ReadValue<string>(SmtpServerKey); }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "SmtpServer");
                }
                ScopeStorage.CurrentScope[SmtpServerKey] = value;
            }
        }

        public static int SmtpPort
        {
            get { return ReadValue<int>(SmtpPortKey); }
            set { ScopeStorage.CurrentScope[SmtpPortKey] = value; }
        }

        public static string From
        {
            get { return ReadValue<string>(FromKey); }
            set { ScopeStorage.CurrentScope[FromKey] = value; }
        }

        public static bool SmtpUseDefaultCredentials
        {
            get { return ReadValue<bool>(SmtpUseDefaultCredentialsKey); }
            set { ScopeStorage.CurrentScope[SmtpUseDefaultCredentialsKey] = value; }
        }

        public static bool EnableSsl
        {
            get { return ReadValue<bool>(EnableSslKey); }
            set { ScopeStorage.CurrentScope[EnableSslKey] = value; }
        }

        public static string UserName
        {
            get { return ReadValue<string>(UserNameKey); }
            set { ScopeStorage.CurrentScope[UserNameKey] = value; }
        }

        public static string Password
        {
            get { return ReadValue<string>(PasswordKey); }
            set { ScopeStorage.CurrentScope[PasswordKey] = value; }
        }

        public static void Send(string to,
                                string subject,
                                string body,
                                string from = null,
                                string cc = null,
                                IEnumerable<string> filesToAttach = null,
                                bool isBodyHtml = true,
                                IEnumerable<string> additionalHeaders = null,
                                string bcc = null,
                                string contentEncoding = null,
                                string headerEncoding = null,
                                string priority = null,
                                string replyTo = null)
        {
            if (filesToAttach != null)
            {
                foreach (string fileName in filesToAttach)
                {
                    if (String.IsNullOrEmpty(fileName))
                    {
                        throw new ArgumentException(HelpersResources.WebMail_ItemInCollectionIsNull, "filesToAttach");
                    }
                }
            }

            if (additionalHeaders != null)
            {
                foreach (string header in additionalHeaders)
                {
                    if (String.IsNullOrEmpty(header))
                    {
                        throw new ArgumentException(HelpersResources.WebMail_ItemInCollectionIsNull, "additionalHeaders");
                    }
                }
            }

            MailPriority priorityValue = MailPriority.Normal;
            if (!String.IsNullOrEmpty(priority) && !ConversionUtil.TryFromStringToEnum(priority, out priorityValue))
            {
                throw new ArgumentException(HelpersResources.WebMail_InvalidPriority, "priority");
            }

            if (String.IsNullOrEmpty(SmtpServer))
            {
                throw new InvalidOperationException(HelpersResources.WebMail_SmtpServerNotSpecified);
            }

            using (MailMessage message = new MailMessage())
            {
                SetPropertiesOnMessage(message, to, subject, body, from, cc, bcc, replyTo, contentEncoding, headerEncoding, priorityValue,
                                       filesToAttach, isBodyHtml, additionalHeaders);
                using (SmtpClient client = new SmtpClient())
                {
                    SetPropertiesOnClient(client);
                    client.Send(message);
                }
            }
        }

        private static TValue ReadValue<TValue>(object key)
        {
            return (TValue)(ScopeStorage.CurrentScope[key] ?? SmtpDefaults.Value[key]);
        }

        private static IDictionary<object, object> ReadSmtpDefaults()
        {
            Dictionary<object, object> smtpDefaults = new Dictionary<object, object>();
            try
            {
                // Create a new SmtpClient object: this will read config & tell us what the default value is
                using (SmtpClient client = new SmtpClient())
                {
                    smtpDefaults[SmtpServerKey] = client.Host;
                    smtpDefaults[SmtpPortKey] = client.Port;
                    smtpDefaults[EnableSslKey] = client.EnableSsl;
                    smtpDefaults[SmtpUseDefaultCredentialsKey] = client.UseDefaultCredentials;

                    var credentials = client.Credentials as NetworkCredential;
                    if (credentials != null)
                    {
                        smtpDefaults[UserNameKey] = credentials.UserName;
                        smtpDefaults[PasswordKey] = credentials.Password;
                    }
                    else
                    {
                        smtpDefaults[UserNameKey] = null;
                        smtpDefaults[PasswordKey] = null;
                    }
                    using (MailMessage message = new MailMessage())
                    {
                        smtpDefaults[FromKey] = (message.From != null) ? message.From.Address : null;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // Due to Bug Dev10 PS 337470 ("SmtpClient reports InvalidOperationException when disposed"), we need to ignore the spurious InvalidOperationException
            }
            return smtpDefaults;
        }

        internal static void SetPropertiesOnClient(SmtpClient client)
        {
            // If no value has been assigned to these properties, at the very worst we will simply 
            // write back the values we just read from the SmtpClient
            if (SmtpServer != null)
            {
                client.Host = SmtpServer;
            }
            client.Port = SmtpPort;
            client.UseDefaultCredentials = SmtpUseDefaultCredentials;
            client.EnableSsl = EnableSsl;
            if (!String.IsNullOrEmpty(UserName))
            {
                client.Credentials = new NetworkCredential(UserName, Password);
            }
        }

        internal static void SetPropertiesOnMessage(MailMessage message, string to, string subject,
                                                    string body, string from, string cc, string bcc, string replyTo,
                                                    string contentEncoding, string headerEncoding, MailPriority priority,
                                                    IEnumerable<string> filesToAttach, bool isBodyHtml,
                                                    IEnumerable<string> additionalHeaders)
        {
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = isBodyHtml;

            if (additionalHeaders != null)
            {
                AssignHeaderValues(message, additionalHeaders);
            }

            if (to != null)
            {
                message.To.Add(to);
            }

            if (!String.IsNullOrEmpty(cc))
            {
                message.CC.Add(cc);
            }

            if (!String.IsNullOrEmpty(bcc))
            {
                message.Bcc.Add(bcc);
            }

            if (!String.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(replyTo);
            }

            if (!String.IsNullOrEmpty(contentEncoding))
            {
                message.BodyEncoding = Encoding.GetEncoding(contentEncoding);
            }

            if (!String.IsNullOrEmpty(headerEncoding))
            {
                message.HeadersEncoding = Encoding.GetEncoding(headerEncoding);
            }

            message.Priority = priority;

            if (from != null)
            {
                message.From = new MailAddress(from);
            }
            else if (!String.IsNullOrEmpty(From))
            {
                message.From = new MailAddress(From);
            }
            else if (message.From == null || String.IsNullOrEmpty(message.From.Address))
            {
                var httpContext = HttpContext.Current;
                if (httpContext != null)
                {
                    message.From = new MailAddress("DoNotReply@" + httpContext.Request.Url.Host);
                }
                else
                {
                    throw new InvalidOperationException(HelpersResources.WebMail_UnableToDetermineFrom);
                }
            }

            if (filesToAttach != null)
            {
                foreach (string file in filesToAttach)
                {
                    if (!Path.IsPathRooted(file) && HttpRuntime.AppDomainAppPath != null)
                    {
                        message.Attachments.Add(new Attachment(Path.Combine(HttpRuntime.AppDomainAppPath, file)));
                    }
                    else
                    {
                        message.Attachments.Add(new Attachment(file));
                    }
                }
            }
        }

        internal static void AssignHeaderValues(MailMessage message, IEnumerable<string> headerValues)
        {
            // Parse the header value. If this 
            foreach (var header in headerValues)
            {
                string key, value;
                if (TryParseHeader(header, out key, out value))
                {
                    // Verify if the header key maps to a property on MailMessage. 
                    Action<MailMessage, string> action;
                    if (_actionableHeaders.TryGetValue(key, out action))
                    {
                        try
                        {
                            action(message, value);
                        }
                        catch (FormatException)
                        {
                            // If the mail address is invalid, swallow the exception.
                        }
                    }
                    message.Headers.Add(key, value);
                }
            }
        }

        /// <summary>
        /// Parses a SMTP Mail header of the format "name: value"
        /// </summary>
        /// <returns>True if the header was parsed.</returns>
        internal static bool TryParseHeader(string header, out string key, out string value)
        {
            int pos = header.IndexOf(':');
            if (pos > 0)
            {
                key = header.Substring(0, pos).TrimEnd();
                value = header.Substring(pos + 1).TrimStart();
                return key.Length > 0 && value.Length > 0;
            }
            key = null;
            value = null;
            return false;
        }

        private static void SetPriority(MailMessage message, string priority)
        {
            MailPriority priorityValue;
            if (!String.IsNullOrEmpty(priority) && ConversionUtil.TryFromStringToEnum(priority, out priorityValue))
            {
                // If we can parse it, set it. Do nothing otherwise
                message.Priority = priorityValue;
            }
        }
    }
}