jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more 
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. 
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with 
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
 
// .NET Compact Framework 1.0 has no support for System.Web.Mail
// SSCLI 1.0 has no support for System.Web.Mail
#if !NETCF && !SSCLI
 
using System;
using System.IO;
 
#if NET_2_0
using System.Net.Mail;
#else
using System.Web.Mail;
#endif
 
using log4net.Layout;
using log4net.Core;
using log4net.Util;
 
namespace log4net.Appender
{
    /// <summary>
    /// Send an e-mail when a specific logging event occurs, typically on errors 
    /// or fatal errors.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The number of logging events delivered in this e-mail depend on
    /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The
    /// <see cref="SmtpAppender"/> keeps only the last
    /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its 
    /// cyclic buffer. This keeps memory requirements at a reasonable level while 
    /// still delivering useful application context.
    /// </para>
    /// <note type="caution">
    /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime.
    /// For these features to be enabled you need to ensure that you are using a version of
    /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are
    /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending
    /// unauthenticated messages to a server listening on port 25 (the default) is supported.
    /// </note>
    /// <para>
    /// Authentication is supported by setting the <see cref="Authentication"/> property to
    /// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>.
    /// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/>
    /// and <see cref="Password"/> properties must also be set.
    /// </para>
    /// <para>
    /// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25.
    /// </para>
    /// </remarks>
    /// <author>Nicko Cadell</author>
    /// <author>Gert Driesen</author>
    public class SmtpAppender : BufferingAppenderSkeleton
    {
        #region Public Instance Constructors
 
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <remarks>
        /// <para>
        /// Default constructor
        /// </para>
        /// </remarks>
        public SmtpAppender()
        {    
        }
 
        #endregion // Public Instance Constructors
 
        #region Public Instance Properties
 
        /// <summary>
        /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions).
        /// </summary>
        /// <value>
        /// <para>
        /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
        /// </para>
        /// <para>
        /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
        /// </para>
        /// </value>
        /// <remarks>
        /// <para>
        /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
        /// </para>
        /// <para>
        /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
        /// </para>
        /// </remarks>
        public string To
        {
            get { return m_to; }
            set { m_to = value; }
        }
 
        /// <summary>
        /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses 
        /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions).
        /// </summary>
        /// <value>
        /// <para>
        /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
        /// </para>
        /// <para>
        /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
        /// </para>
        /// </value>
        /// <remarks>
        /// <para>
        /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses.
        /// </para>
        /// <para>
        /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses.
        /// </para>
        /// </remarks>
        public string Cc
        {
            get { return m_cc; }
            set { m_cc = value; }
        }
 
        /// <summary>
        /// Gets or sets a semicolon-delimited list of recipient e-mail addresses
        /// that will be blind carbon copied.
        /// </summary>
        /// <value>
        /// A semicolon-delimited list of e-mail addresses.
        /// </value>
        /// <remarks>
        /// <para>
        /// A semicolon-delimited list of recipient e-mail addresses.
        /// </para>
        /// </remarks>
        public string Bcc
        {
            get { return m_bcc; }
            set { m_bcc = value; }
        }
 
        /// <summary>
        /// Gets or sets the e-mail address of the sender.
        /// </summary>
        /// <value>
        /// The e-mail address of the sender.
        /// </value>
        /// <remarks>
        /// <para>
        /// The e-mail address of the sender.
        /// </para>
        /// </remarks>
        public string From 
        {
            get { return m_from; }
            set { m_from = value; }
        }
 
        /// <summary>
        /// Gets or sets the subject line of the e-mail message.
        /// </summary>
        /// <value>
        /// The subject line of the e-mail message.
        /// </value>
        /// <remarks>
        /// <para>
        /// The subject line of the e-mail message.
        /// </para>
        /// </remarks>
        public string Subject 
        {
            get { return m_subject; }
            set { m_subject = value; }
        }
  
        /// <summary>
        /// Gets or sets the name of the SMTP relay mail server to use to send 
        /// the e-mail messages.
        /// </summary>
        /// <value>
        /// The name of the e-mail relay server. If SmtpServer is not set, the 
        /// name of the local SMTP server is used.
        /// </value>
        /// <remarks>
        /// <para>
        /// The name of the e-mail relay server. If SmtpServer is not set, the 
        /// name of the local SMTP server is used.
        /// </para>
        /// </remarks>
        public string SmtpHost
        {
            get { return m_smtpHost; }
            set { m_smtpHost = value; }
        }
 
        /// <summary>
        /// Obsolete
        /// </summary>
        /// <remarks>
        /// Use the BufferingAppenderSkeleton Fix methods instead 
        /// </remarks>
        /// <remarks>
        /// <para>
        /// Obsolete property.
        /// </para>
        /// </remarks>
        [Obsolete("Use the BufferingAppenderSkeleton Fix methods")]
        public bool LocationInfo
        {
            get { return false; }
            set { ; }
        }
 
        /// <summary>
        /// The mode to use to authentication with the SMTP server
        /// </summary>
        /// <remarks>
        /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
        /// <para>
        /// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>, 
        /// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>. 
        /// The default value is <see cref="SmtpAuthentication.None"/>. When using 
        /// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/> 
        /// and <see cref="Password"/> to use to authenticate.
        /// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current
        /// thread, if impersonating, or the process will be used to authenticate. 
        /// </para>
        /// </remarks>
        public SmtpAuthentication Authentication
        {
            get { return m_authentication; }
            set { m_authentication = value; }
        }
 
        /// <summary>
        /// The username to use to authenticate with the SMTP server
        /// </summary>
        /// <remarks>
        /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
        /// <para>
        /// A <see cref="Username"/> and <see cref="Password"/> must be specified when 
        /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, 
        /// otherwise the username will be ignored. 
        /// </para>
        /// </remarks>
        public string Username
        {
            get { return m_username; }
            set { m_username = value; }
        }
 
        /// <summary>
        /// The password to use to authenticate with the SMTP server
        /// </summary>
        /// <remarks>
        /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note>
        /// <para>
        /// A <see cref="Username"/> and <see cref="Password"/> must be specified when 
        /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, 
        /// otherwise the password will be ignored. 
        /// </para>
        /// </remarks>
        public string Password
        {
            get { return m_password; }
            set { m_password = value; }
        }
 
        /// <summary>
        /// The port on which the SMTP server is listening
        /// </summary>
        /// <remarks>
        /// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note>
        /// <para>
        /// The port on which the SMTP server is listening. The default
        /// port is <c>25</c>. The Port can only be changed when running on
        /// the MS .NET 1.1 runtime.
        /// </para>
        /// </remarks>
        public int Port
        {
            get { return m_port; }
            set { m_port = value; }
        }
 
        /// <summary>
        /// Gets or sets the priority of the e-mail message
        /// </summary>
        /// <value>
        /// One of the <see cref="MailPriority"/> values.
        /// </value>
        /// <remarks>
        /// <para>
        /// Sets the priority of the e-mails generated by this
        /// appender. The default priority is <see cref="MailPriority.Normal"/>.
        /// </para>
        /// <para>
        /// If you are using this appender to report errors then
        /// you may want to set the priority to <see cref="MailPriority.High"/>.
        /// </para>
        /// </remarks>
        public MailPriority Priority
        {
            get { return m_mailPriority; }
            set { m_mailPriority = value; }
        }
 
#if NET_2_0
        /// <summary>
        /// Enable or disable use of SSL when sending e-mail message
        /// </summary>
        /// <remarks>
        /// This is available on MS .NET 2.0 runtime and higher
        /// </remarks>
        public bool EnableSsl
        {
            get { return m_enableSsl; }
            set { m_enableSsl = value; }
        }
 
        /// <summary>
        /// Gets or sets the reply-to e-mail address.
        /// </summary>
        /// <remarks>
        /// This is available on MS .NET 2.0 runtime and higher
        /// </remarks>
        public string ReplyTo
        {
            get { return m_replyTo; }
            set { m_replyTo = value; }
        }
#endif
 
        #endregion // Public Instance Properties
 
        #region Override implementation of BufferingAppenderSkeleton
 
        /// <summary>
        /// Sends the contents of the cyclic buffer as an e-mail message.
        /// </summary>
        /// <param name="events">The logging events to send.</param>
        override protected void SendBuffer(LoggingEvent[] events) 
        {
            // Note: this code already owns the monitor for this
            // appender. This frees us from needing to synchronize again.
            try 
            {      
                StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
 
                string t = Layout.Header;
                if (t != null)
                {
                    writer.Write(t);
                }
 
                for(int i = 0; i < events.Length; i++) 
                {
                    // Render the event and append the text to the buffer
                    RenderLoggingEvent(writer, events[i]);
                }
 
                t = Layout.Footer;
                if (t != null)
                {
                    writer.Write(t);
                }
 
                SendEmail(writer.ToString());
            } 
            catch(Exception e) 
            {
                ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
            }
        }
 
        #endregion // Override implementation of BufferingAppenderSkeleton
 
        #region Override implementation of AppenderSkeleton
 
        /// <summary>
        /// This appender requires a <see cref="Layout"/> to be set.
        /// </summary>
        /// <value><c>true</c></value>
        /// <remarks>
        /// <para>
        /// This appender requires a <see cref="Layout"/> to be set.
        /// </para>
        /// </remarks>
        override protected bool RequiresLayout
        {
            get { return true; }
        }
 
        #endregion // Override implementation of AppenderSkeleton
 
        #region Protected Methods
 
        /// <summary>
        /// Send the email message
        /// </summary>
        /// <param name="messageBody">the body text to include in the mail</param>
        virtual protected void SendEmail(string messageBody)
        {
#if NET_2_0
            // .NET 2.0 has a new API for SMTP email System.Net.Mail
            // This API supports credentials and multiple hosts correctly.
            // The old API is deprecated.
 
            // Create and configure the smtp client
            SmtpClient smtpClient = new SmtpClient();
            if (!String.IsNullOrEmpty(m_smtpHost))
            {
                smtpClient.Host = m_smtpHost;
            }
            smtpClient.Port = m_port;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl = m_enableSsl;
 
            if (m_authentication == SmtpAuthentication.Basic)
            {
                // Perform basic authentication
                smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password);
            }
            else if (m_authentication == SmtpAuthentication.Ntlm)
            {
                // Perform integrated authentication (NTLM)
                smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
 
            using (MailMessage mailMessage = new MailMessage())
            {
                mailMessage.Body = messageBody;
                mailMessage.From = new MailAddress(m_from);
                mailMessage.To.Add(m_to);
                if (!String.IsNullOrEmpty(m_cc))
                {
                    mailMessage.CC.Add(m_cc);
                }
                if (!String.IsNullOrEmpty(m_bcc))
                {
                    mailMessage.Bcc.Add(m_bcc);
                }
                if (!String.IsNullOrEmpty(m_replyTo))
                {
                    // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete:
                    // 'ReplyTo is obsoleted for this type.  Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202'
#if !NET_4_0
                    mailMessage.ReplyTo = new MailAddress(m_replyTo);
#else
                    mailMessage.ReplyToList.Add(new MailAddress(m_replyTo));
#endif
                }
                mailMessage.Subject = m_subject;
                mailMessage.Priority = m_mailPriority;
 
                // TODO: Consider using SendAsync to send the message without blocking. This would be a change in
                // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors.
                smtpClient.Send(mailMessage);
            }
#else
                // .NET 1.x uses the System.Web.Mail API for sending Mail
 
                MailMessage mailMessage = new MailMessage();
                mailMessage.Body = messageBody;
                mailMessage.From = m_from;
                mailMessage.To = m_to;
                if (m_cc != null && m_cc.Length > 0)
                {
                    mailMessage.Cc = m_cc;
                }
                if (m_bcc != null && m_bcc.Length > 0)
                {
                    mailMessage.Bcc = m_bcc;
                }
                mailMessage.Subject = m_subject;
                mailMessage.Priority = m_mailPriority;
 
#if NET_1_1
                // The Fields property on the MailMessage allows the CDO properties to be set directly.
                // This property is only available on .NET Framework 1.1 and the implementation must understand
                // the CDO properties. For details of the fields available in CDO see:
                //
                // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp
                // 
 
                try
                {
                    if (m_authentication == SmtpAuthentication.Basic)
                    {
                        // Perform basic authentication
                        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
                        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username);
                        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password);
                    }
                    else if (m_authentication == SmtpAuthentication.Ntlm)
                    {
                        // Perform integrated authentication (NTLM)
                        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2);
                    }
 
                    // Set the port if not the default value
                    if (m_port != 25) 
                    {
                        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port);
                    }
                }
                catch(MissingMethodException missingMethodException)
                {
                    // If we were compiled against .NET 1.1 but are running against .NET 1.0 then
                    // we will get a MissingMethodException when accessing the MailMessage.Fields property.
 
                    ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException);
                }
#else
                if (m_authentication != SmtpAuthentication.None)
                {
                    ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
                }
 
                if (m_port != 25)
                {
                    ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net");
                }
#endif // if NET_1_1
 
                if (m_smtpHost != null && m_smtpHost.Length > 0)
                {
                    SmtpMail.SmtpServer = m_smtpHost;
                }
 
                SmtpMail.Send(mailMessage);
#endif // if NET_2_0
        }
 
        #endregion // Protected Methods
 
        #region Private Instance Fields
 
        private string m_to;
        private string m_cc;
        private string m_bcc;
        private string m_from;
        private string m_subject;
        private string m_smtpHost;
 
        // authentication fields
        private SmtpAuthentication m_authentication = SmtpAuthentication.None;
        private string m_username;
        private string m_password;
 
        // server port, default port 25
        private int m_port = 25;
 
        private MailPriority m_mailPriority = MailPriority.Normal;
 
#if NET_2_0
        private bool m_enableSsl = false;
        private string m_replyTo;
#endif
 
        #endregion // Private Instance Fields
 
        #region SmtpAuthentication Enum
 
        /// <summary>
        /// Values for the <see cref="SmtpAppender.Authentication"/> property.
        /// </summary>
        /// <remarks>
        /// <para>
        /// SMTP authentication modes.
        /// </para>
        /// </remarks>
        public enum SmtpAuthentication
        {
            /// <summary>
            /// No authentication
            /// </summary>
            None,
 
            /// <summary>
            /// Basic authentication.
            /// </summary>
            /// <remarks>
            /// Requires a username and password to be supplied
            /// </remarks>
            Basic,
 
            /// <summary>
            /// Integrated authentication
            /// </summary>
            /// <remarks>
            /// Uses the Windows credentials from the current thread or process to authenticate.
            /// </remarks>
            Ntlm
        }
 
        #endregion // SmtpAuthentication Enum
    }
}
 
#endif // !NETCF && !SSCLI