Skip to content

Commit 7bf2afd

Browse files
Release 4: .NET standard 2.0 only, CSL complaint, Cleanup (#131)
* 4.0 release:.NET Standard 2.0 only * Update dependencies * cleanup * update smtpserver package * [assembly:CLSCompliant(true)] * public helper method to internal * cleanup * version 4.0 * cleanup * changelog * ignore ref folder * [CLSCompliant(false)] for SecureSocketOption * changelog * cleanup * 2021 * cleanup * update docs
1 parent f3c2de2 commit 7bf2afd

15 files changed

+126
-253
lines changed

azure-pipelines.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ variables:
1313
Solution: 'src/NLog.MailKit.sln'
1414
BuildPlatform: 'Any CPU'
1515
BuildConfiguration: 'Release'
16-
Version: '3.4.0'
16+
Version: '4.0.0'
1717
FullVersion: '$(Version).$(Build.BuildId)'
1818

1919
steps:
@@ -54,6 +54,7 @@ steps:
5454
testAssemblyVer2: |
5555
**\*.tests.dll
5656
!**\obj\**
57+
!**\ref\**
5758
codeCoverageEnabled: true
5859
platform: '$(BuildPlatform)'
5960
configuration: '$(BuildConfiguration)'

src/NLog.MailKit/MailTarget.cs

Lines changed: 48 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//
2-
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
2+
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
33
//
44
// All rights reserved.
55
//
@@ -31,7 +31,6 @@
3131
// THE POSSIBILITY OF SUCH DAMAGE.
3232
//
3333

34-
3534
using System;
3635
using System.Collections.Generic;
3736
using System.ComponentModel;
@@ -42,8 +41,8 @@
4241
using MimeKit.Text;
4342
using NLog.Common;
4443
using NLog.Config;
45-
using NLog.Internal;
4644
using NLog.Layouts;
45+
using NLog.MailKit.Util;
4746
using NLog.Targets;
4847

4948
namespace NLog.MailKit
@@ -54,7 +53,7 @@ namespace NLog.MailKit
5453
/// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso>
5554
/// <example>
5655
/// <p>
57-
/// To set up the target in the <a href="config.html">configuration file</a>,
56+
/// To set up the target in the <a href="config.html">configuration file</a>,
5857
/// use the following syntax:
5958
/// </p>
6059
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" />
@@ -71,7 +70,7 @@ namespace NLog.MailKit
7170
/// which lets you send multiple log messages in single mail
7271
/// </p>
7372
/// <p>
74-
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
73+
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
7574
/// use the following syntax:
7675
/// </p>
7776
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" />
@@ -91,7 +90,6 @@ public class MailTarget : TargetWithLayoutHeaderAndFooter
9190
/// <remarks>
9291
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
9392
/// </remarks>
94-
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")]
9593
public MailTarget()
9694
{
9795
Body = "${message}${newline}";
@@ -209,18 +207,20 @@ public Layout Body
209207
/// <summary>
210208
/// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server.
211209
///
212-
/// See also <see cref="SecureSocketOption"/>
210+
/// See also <see cref="SecureSocketOption" />
213211
/// </summary>
214-
/// <docgen category='SMTP Options' order='14' />.
212+
/// <docgen category='SMTP Options' order='14' />
213+
/// .
215214
[DefaultValue(false)]
216215
public bool EnableSsl { get; set; }
217216

218217
/// <summary>
219-
/// Provides a way of specifying the SSL and/or TLS encryption
218+
/// Provides a way of specifying the SSL and/or TLS encryption
220219
///
221-
/// If <see cref="EnableSsl"/> is <c>true</c>, then <see cref="SecureSocketOptions.SslOnConnect"/> will be used.
220+
/// If <see cref="EnableSsl" /> is <c>true</c>, then <see cref="SecureSocketOptions.SslOnConnect" /> will be used.
222221
/// </summary>
223222
[DefaultValue(SecureSocketOptions.StartTlsWhenAvailable)]
223+
[CLSCompliant(false)]
224224
public SecureSocketOptions SecureSocketOption { get; set; }
225225

226226
/// <summary>
@@ -233,7 +233,8 @@ public Layout Body
233233
/// <summary>
234234
/// Gets or sets a value indicating whether SmtpClient should ignore invalid certificate.
235235
/// </summary>
236-
/// <docgen category='SMTP Options' order='16' />.
236+
/// <docgen category='SMTP Options' order='16' />
237+
/// .
237238
[DefaultValue(false)]
238239
public bool SkipCertificateValidation { get; set; }
239240

@@ -243,9 +244,9 @@ public Layout Body
243244
public Layout Priority { get; set; }
244245

245246
/// <summary>
246-
/// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags.
247+
/// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br /> tags.
247248
/// </summary>
248-
/// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks>
249+
/// <remarks>Only happens when <see cref="Html" /> is set to true.</remarks>
249250
[DefaultValue(false)]
250251
public bool ReplaceNewlineWithBrTagInHtml { get; set; }
251252

@@ -265,24 +266,6 @@ protected override void Write(AsyncLogEventInfo logEvent)
265266
Write((IList<AsyncLogEventInfo>)new[] { logEvent });
266267
}
267268

268-
#if !NETSTANDARD2_0
269-
270-
/// <summary>
271-
/// NOTE! Will soon be marked obsolete. Instead override Write(IList{AsyncLogEventInfo} logEvents)
272-
///
273-
/// Writes an array of logging events to the log target. By default it iterates on all
274-
/// events and passes them to "Write" method. Inheriting classes can use this method to
275-
/// optimize batch writes.
276-
/// </summary>
277-
/// <param name="logEvents">Logging events to be written out.</param>
278-
[Obsolete("Write(AsyncLogEventInfo[]) is obsolete. Override Write(IList{AsyncLogEventInfo} logEvents) instead.", true)]
279-
protected override void Write(AsyncLogEventInfo[] logEvents)
280-
{
281-
Write((IList<AsyncLogEventInfo>)logEvents);
282-
}
283-
284-
#endif
285-
286269
/// <summary>
287270
/// Renders an array logging events.
288271
/// </summary>
@@ -306,16 +289,14 @@ protected override void InitializeTarget()
306289
InternalLogger.Debug("Init mailtarget with mailkit");
307290
CheckRequiredParameters();
308291

309-
if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
292+
if (SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
310293
{
311294
throw new NLogConfigurationException("Ntlm not yet supported");
312295
}
313296

314297
base.InitializeTarget();
315298
}
316299

317-
318-
319300
/// <summary>
320301
/// Create mail and send with SMTP
321302
/// </summary>
@@ -329,8 +310,8 @@ private void ProcessSingleMailMessage(IList<AsyncLogEventInfo> events)
329310
throw new NLogRuntimeException("We need at least one event.");
330311
}
331312

332-
LogEventInfo firstEvent = events[0].LogEvent;
333-
LogEventInfo lastEvent = events[events.Count - 1].LogEvent;
313+
var firstEvent = events[0].LogEvent;
314+
var lastEvent = events[events.Count - 1].LogEvent;
334315

335316
// unbuffered case, create a local buffer, append header, body and footer
336317
var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent);
@@ -351,10 +332,12 @@ private void ProcessSingleMailMessage(IList<AsyncLogEventInfo> events)
351332
var secureSocketOptions = EnableSsl ? SecureSocketOptions.SslOnConnect : SecureSocketOption;
352333
InternalLogger.Debug("Sending mail to {0} using {1}:{2} (socket option={3})", message.To, renderedHost, SmtpPort, secureSocketOptions);
353334
InternalLogger.Trace(" Subject: '{0}'", message.Subject);
354-
InternalLogger.Trace(" From: '{0}'", message.From.ToString());
335+
InternalLogger.Trace(" From: '{0}'", message.From);
355336

356337
if (SkipCertificateValidation)
338+
{
357339
client.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
340+
}
358341

359342

360343
client.Connect(renderedHost, SmtpPort, secureSocketOptions);
@@ -366,7 +349,7 @@ private void ProcessSingleMailMessage(IList<AsyncLogEventInfo> events)
366349

367350
// Note: only needed if the SMTP server requires authentication
368351

369-
if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
352+
if (SmtpAuthentication == SmtpAuthenticationMode.Basic)
370353
{
371354
var userName = SmtpUserName?.Render(lastEvent);
372355
var password = SmtpPassword?.Render(lastEvent);
@@ -423,7 +406,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, Lo
423406
}
424407
}
425408

426-
foreach (AsyncLogEventInfo eventInfo in events)
409+
foreach (var eventInfo in events)
427410
{
428411
bodyBuffer.Append(Layout.Render(eventInfo.LogEvent));
429412
if (AddNewLines)
@@ -440,6 +423,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, Lo
440423
bodyBuffer.Append("\n");
441424
}
442425
}
426+
443427
return bodyBuffer;
444428
}
445429

@@ -459,8 +443,8 @@ private void CheckRequiredParameters()
459443
/// <summary>
460444
/// Create key for grouping. Needed for multiple events in one mailmessage
461445
/// </summary>
462-
/// <param name="logEvent">event for rendering layouts </param>
463-
///<returns>string to group on</returns>
446+
/// <param name="logEvent">event for rendering layouts </param>
447+
/// <returns>string to group on</returns>
464448
private string GetSmtpSettingsKey(LogEventInfo logEvent)
465449
{
466450
var sb = new StringBuilder();
@@ -472,26 +456,25 @@ private string GetSmtpSettingsKey(LogEventInfo logEvent)
472456
AppendLayout(sb, logEvent, SmtpServer);
473457
AppendLayout(sb, logEvent, SmtpPassword);
474458
AppendLayout(sb, logEvent, SmtpUserName);
475-
476-
459+
477460
return sb.ToString();
478461
}
479462

480463
/// <summary>
481464
/// Append rendered layout to the stringbuilder
482465
/// </summary>
483466
/// <param name="sb">append to this</param>
484-
/// <param name="logEvent">event for rendering <paramref name="layout"/></param>
467+
/// <param name="logEvent">event for rendering <paramref name="layout" /></param>
485468
/// <param name="layout">append if not <c>null</c></param>
486469
private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout)
487470
{
488471
sb.Append("|");
489472
if (layout != null)
473+
{
490474
sb.Append(layout.Render(logEvent));
475+
}
491476
}
492477

493-
494-
495478
/// <summary>
496479
/// Create the mailmessage with the addresses, properties and body.
497480
/// </summary>
@@ -505,6 +488,7 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body)
505488
{
506489
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
507490
}
491+
508492
msg.From.Add(MailboxAddress.Parse(renderedFrom));
509493

510494
var addedTo = AddAddresses(msg.To, To, lastEvent);
@@ -523,22 +507,21 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body)
523507
if (Priority != null)
524508
{
525509
var renderedPriority = Priority.Render(lastEvent);
526-
MessagePriority messagePriority;
527-
messagePriority = ParseMessagePriority(renderedPriority);
528-
msg.Priority = messagePriority;
510+
msg.Priority = ParseMessagePriority(renderedPriority);
529511
}
530512

531513
TextPart CreateBodyPart()
532514
{
533515
var newBody = body;
534516
if (Html && ReplaceNewlineWithBrTagInHtml)
517+
{
535518
newBody = newBody?.Replace(Environment.NewLine, "<br/>");
519+
}
520+
536521
return new TextPart(Html ? TextFormat.Html : TextFormat.Plain)
537522
{
538523
Text = newBody,
539524
ContentType = { Charset = Encoding?.WebName }
540-
541-
542525
};
543526
}
544527

@@ -547,7 +530,7 @@ TextPart CreateBodyPart()
547530
return msg;
548531
}
549532

550-
public static MessagePriority ParseMessagePriority(string priority)
533+
internal static MessagePriority ParseMessagePriority(string priority)
551534
{
552535
if (string.IsNullOrWhiteSpace(priority))
553536
{
@@ -559,10 +542,12 @@ public static MessagePriority ParseMessagePriority(string priority)
559542
{
560543
return MessagePriority.Urgent;
561544
}
545+
562546
if (priority.Equals("Low", StringComparison.OrdinalIgnoreCase))
563547
{
564548
return MessagePriority.NonUrgent;
565549
}
550+
566551
MessagePriority messagePriority;
567552
try
568553
{
@@ -580,26 +565,27 @@ public static MessagePriority ParseMessagePriority(string priority)
580565
}
581566

582567
/// <summary>
583-
/// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/>
568+
/// Render <paramref name="layout" /> and add the addresses to <paramref name="mailAddressCollection" />
584569
/// </summary>
585570
/// <param name="mailAddressCollection">Addresses appended to this list</param>
586571
/// <param name="layout">layout with addresses, ; separated</param>
587-
/// <param name="logEvent">event for rendering the <paramref name="layout"/></param>
572+
/// <param name="logEvent">event for rendering the <paramref name="layout" /></param>
588573
/// <returns>added a address?</returns>
589574
private static bool AddAddresses(InternetAddressList mailAddressCollection, Layout layout, LogEventInfo logEvent)
590575
{
576+
if (layout == null)
577+
{
578+
return false;
579+
}
580+
591581
var added = false;
592-
if (layout != null)
582+
foreach (var mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
593583
{
594-
foreach (string mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
595-
{
596-
mailAddressCollection.Add(MailboxAddress.Parse(mail));
597-
added = true;
598-
}
584+
mailAddressCollection.Add(MailboxAddress.Parse(mail));
585+
added = true;
599586
}
600587

601588
return added;
602589
}
603590
}
604-
}
605-
591+
}

0 commit comments

Comments
 (0)