Skip to content

Commit

Permalink
Release 4: .NET standard 2.0 only, CSL complaint, Cleanup (#131)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
304NotModified authored Nov 6, 2021
1 parent f3c2de2 commit 7bf2afd
Show file tree
Hide file tree
Showing 15 changed files with 126 additions and 253 deletions.
3 changes: 2 additions & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ variables:
Solution: 'src/NLog.MailKit.sln'
BuildPlatform: 'Any CPU'
BuildConfiguration: 'Release'
Version: '3.4.0'
Version: '4.0.0'
FullVersion: '$(Version).$(Build.BuildId)'

steps:
Expand Down Expand Up @@ -54,6 +54,7 @@ steps:
testAssemblyVer2: |
**\*.tests.dll
!**\obj\**
!**\ref\**
codeCoverageEnabled: true
platform: '$(BuildPlatform)'
configuration: '$(BuildConfiguration)'
Expand Down
110 changes: 48 additions & 62 deletions src/NLog.MailKit/MailTarget.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
Expand Down Expand Up @@ -31,7 +31,6 @@
// THE POSSIBILITY OF SUCH DAMAGE.
//


using System;
using System.Collections.Generic;
using System.ComponentModel;
Expand All @@ -42,8 +41,8 @@
using MimeKit.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.MailKit.Util;
using NLog.Targets;

namespace NLog.MailKit
Expand All @@ -54,7 +53,7 @@ namespace NLog.MailKit
/// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" />
Expand All @@ -71,7 +70,7 @@ namespace NLog.MailKit
/// which lets you send multiple log messages in single mail
/// </p>
/// <p>
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" />
Expand All @@ -91,7 +90,6 @@ public class MailTarget : TargetWithLayoutHeaderAndFooter
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")]
public MailTarget()
{
Body = "${message}${newline}";
Expand Down Expand Up @@ -209,18 +207,20 @@ public Layout Body
/// <summary>
/// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server.
///
/// See also <see cref="SecureSocketOption"/>
/// See also <see cref="SecureSocketOption" />
/// </summary>
/// <docgen category='SMTP Options' order='14' />.
/// <docgen category='SMTP Options' order='14' />
/// .
[DefaultValue(false)]
public bool EnableSsl { get; set; }

/// <summary>
/// Provides a way of specifying the SSL and/or TLS encryption
/// Provides a way of specifying the SSL and/or TLS encryption
///
/// If <see cref="EnableSsl"/> is <c>true</c>, then <see cref="SecureSocketOptions.SslOnConnect"/> will be used.
/// If <see cref="EnableSsl" /> is <c>true</c>, then <see cref="SecureSocketOptions.SslOnConnect" /> will be used.
/// </summary>
[DefaultValue(SecureSocketOptions.StartTlsWhenAvailable)]
[CLSCompliant(false)]
public SecureSocketOptions SecureSocketOption { get; set; }

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

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

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

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

#if !NETSTANDARD2_0

/// <summary>
/// NOTE! Will soon be marked obsolete. Instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Write(AsyncLogEventInfo[]) is obsolete. Override Write(IList{AsyncLogEventInfo} logEvents) instead.", true)]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}

#endif

/// <summary>
/// Renders an array logging events.
/// </summary>
Expand All @@ -306,16 +289,14 @@ protected override void InitializeTarget()
InternalLogger.Debug("Init mailtarget with mailkit");
CheckRequiredParameters();

if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
if (SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
{
throw new NLogConfigurationException("Ntlm not yet supported");
}

base.InitializeTarget();
}



/// <summary>
/// Create mail and send with SMTP
/// </summary>
Expand All @@ -329,8 +310,8 @@ private void ProcessSingleMailMessage(IList<AsyncLogEventInfo> events)
throw new NLogRuntimeException("We need at least one event.");
}

LogEventInfo firstEvent = events[0].LogEvent;
LogEventInfo lastEvent = events[events.Count - 1].LogEvent;
var firstEvent = events[0].LogEvent;
var lastEvent = events[events.Count - 1].LogEvent;

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

if (SkipCertificateValidation)
{
client.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
}


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

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

if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
if (SmtpAuthentication == SmtpAuthenticationMode.Basic)
{
var userName = SmtpUserName?.Render(lastEvent);
var password = SmtpPassword?.Render(lastEvent);
Expand Down Expand Up @@ -423,7 +406,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, Lo
}
}

foreach (AsyncLogEventInfo eventInfo in events)
foreach (var eventInfo in events)
{
bodyBuffer.Append(Layout.Render(eventInfo.LogEvent));
if (AddNewLines)
Expand All @@ -440,6 +423,7 @@ private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, Lo
bodyBuffer.Append("\n");
}
}

return bodyBuffer;
}

Expand All @@ -459,8 +443,8 @@ private void CheckRequiredParameters()
/// <summary>
/// Create key for grouping. Needed for multiple events in one mailmessage
/// </summary>
/// <param name="logEvent">event for rendering layouts </param>
///<returns>string to group on</returns>
/// <param name="logEvent">event for rendering layouts </param>
/// <returns>string to group on</returns>
private string GetSmtpSettingsKey(LogEventInfo logEvent)
{
var sb = new StringBuilder();
Expand All @@ -472,26 +456,25 @@ private string GetSmtpSettingsKey(LogEventInfo logEvent)
AppendLayout(sb, logEvent, SmtpServer);
AppendLayout(sb, logEvent, SmtpPassword);
AppendLayout(sb, logEvent, SmtpUserName);



return sb.ToString();
}

/// <summary>
/// Append rendered layout to the stringbuilder
/// </summary>
/// <param name="sb">append to this</param>
/// <param name="logEvent">event for rendering <paramref name="layout"/></param>
/// <param name="logEvent">event for rendering <paramref name="layout" /></param>
/// <param name="layout">append if not <c>null</c></param>
private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout)
{
sb.Append("|");
if (layout != null)
{
sb.Append(layout.Render(logEvent));
}
}



/// <summary>
/// Create the mailmessage with the addresses, properties and body.
/// </summary>
Expand All @@ -505,6 +488,7 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body)
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
}

msg.From.Add(MailboxAddress.Parse(renderedFrom));

var addedTo = AddAddresses(msg.To, To, lastEvent);
Expand All @@ -523,22 +507,21 @@ private MimeMessage CreateMailMessage(LogEventInfo lastEvent, string body)
if (Priority != null)
{
var renderedPriority = Priority.Render(lastEvent);
MessagePriority messagePriority;
messagePriority = ParseMessagePriority(renderedPriority);
msg.Priority = messagePriority;
msg.Priority = ParseMessagePriority(renderedPriority);
}

TextPart CreateBodyPart()
{
var newBody = body;
if (Html && ReplaceNewlineWithBrTagInHtml)
{
newBody = newBody?.Replace(Environment.NewLine, "<br/>");
}

return new TextPart(Html ? TextFormat.Html : TextFormat.Plain)
{
Text = newBody,
ContentType = { Charset = Encoding?.WebName }


};
}

Expand All @@ -547,7 +530,7 @@ TextPart CreateBodyPart()
return msg;
}

public static MessagePriority ParseMessagePriority(string priority)
internal static MessagePriority ParseMessagePriority(string priority)
{
if (string.IsNullOrWhiteSpace(priority))
{
Expand All @@ -559,10 +542,12 @@ public static MessagePriority ParseMessagePriority(string priority)
{
return MessagePriority.Urgent;
}

if (priority.Equals("Low", StringComparison.OrdinalIgnoreCase))
{
return MessagePriority.NonUrgent;
}

MessagePriority messagePriority;
try
{
Expand All @@ -580,26 +565,27 @@ public static MessagePriority ParseMessagePriority(string priority)
}

/// <summary>
/// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/>
/// Render <paramref name="layout" /> and add the addresses to <paramref name="mailAddressCollection" />
/// </summary>
/// <param name="mailAddressCollection">Addresses appended to this list</param>
/// <param name="layout">layout with addresses, ; separated</param>
/// <param name="logEvent">event for rendering the <paramref name="layout"/></param>
/// <param name="logEvent">event for rendering the <paramref name="layout" /></param>
/// <returns>added a address?</returns>
private static bool AddAddresses(InternetAddressList mailAddressCollection, Layout layout, LogEventInfo logEvent)
{
if (layout == null)
{
return false;
}

var added = false;
if (layout != null)
foreach (var mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
foreach (string mail in layout.Render(logEvent).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
mailAddressCollection.Add(MailboxAddress.Parse(mail));
added = true;
}
mailAddressCollection.Add(MailboxAddress.Parse(mail));
added = true;
}

return added;
}
}
}

}
Loading

0 comments on commit 7bf2afd

Please sign in to comment.