Skip to content

Commit 82ecf29

Browse files
authored
MailTarget - Validate Email Address on InitializeTarget (#241)
1 parent 07002d9 commit 82ecf29

2 files changed

Lines changed: 87 additions & 7 deletions

File tree

src/NLog.MailKit/MailTarget.cs

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -300,10 +300,35 @@ protected override void InitializeTarget()
300300
{
301301
InternalLogger.Debug("Init mailtarget with mailkit");
302302
CheckRequiredParameters();
303-
303+
ValidateFixedEmailAddress(From, nameof(From));
304+
ValidateFixedEmailAddress(To, nameof(To));
305+
ValidateFixedEmailAddress(Cc, nameof(Cc));
306+
ValidateFixedEmailAddress(Bcc, nameof(Bcc));
304307
base.InitializeTarget();
305308
}
306309

310+
private void ValidateFixedEmailAddress(Layout? emailAddress, string emailAddressType)
311+
{
312+
if (!ReferenceEquals(emailAddress, Layout.Empty) && emailAddress is SimpleLayout simpleLayout && simpleLayout.IsFixedText)
313+
{
314+
var mailAddressCollection = new InternetAddressList();
315+
try
316+
{
317+
if (!AddAddresses(mailAddressCollection, emailAddress, LogEventInfo.CreateNullEvent(), allowThrow: true))
318+
throw new NLogConfigurationException(string.Format(RequiredPropertyIsEmptyFormat, emailAddressType));
319+
}
320+
catch (NLogConfigurationException)
321+
{
322+
throw;
323+
}
324+
catch (Exception ex)
325+
{
326+
var nlogConfigException = new NLogConfigurationException($"MailTarget: Invalid {emailAddressType}-email-address: {simpleLayout.FixedText}", ex);
327+
throw nlogConfigException;
328+
}
329+
}
330+
}
331+
307332
/// <summary>
308333
/// Create mail and send with SMTP
309334
/// </summary>
@@ -500,12 +525,12 @@ internal string ResolvePickupDirectoryLocationFilePath(string pickupDirectoryLoc
500525

501526
private void CheckRequiredParameters()
502527
{
503-
if (From is null || ReferenceEquals(From, Layout.Empty))
528+
if (IsEmptyLayout(From))
504529
{
505530
throw new NLogConfigurationException("MailTarget - From address is required");
506531
}
507532

508-
if (To is null || ReferenceEquals(To, Layout.Empty))
533+
if (IsEmptyLayout(To) && IsEmptyLayout(Cc) && IsEmptyLayout(Bcc))
509534
{
510535
throw new NLogConfigurationException("MailTarget - To address is required");
511536
}
@@ -516,17 +541,22 @@ private void CheckRequiredParameters()
516541
throw new NLogConfigurationException("MailTarget - SmtpAuthentication NTLM not yet supported");
517542
}
518543

519-
if ((PickupDirectoryLocation is null || ReferenceEquals(PickupDirectoryLocation, Layout.Empty)) && (SmtpServer is null || ReferenceEquals(SmtpServer, Layout.Empty)))
544+
if (IsEmptyLayout(PickupDirectoryLocation) && IsEmptyLayout(SmtpServer))
520545
{
521546
throw new NLogConfigurationException("MailTarget - SmtpServer is required");
522547
}
523548

524-
if (smtpAuthentication == SmtpAuthenticationMode.OAuth2 && (SmtpUserName is null || ReferenceEquals(SmtpUserName, Layout.Empty) || SmtpPassword is null || ReferenceEquals(SmtpPassword, Layout.Empty)))
549+
if (smtpAuthentication == SmtpAuthenticationMode.OAuth2 && (IsEmptyLayout(SmtpUserName) || IsEmptyLayout(SmtpPassword)))
525550
{
526551
throw new NLogConfigurationException("MailTarget - SmtpUserName (OAuth UserName) and SmtpPassword (OAuth AccessToken) is required when SmtpAuthentication = OAuth2");
527552
}
528553
}
529554

555+
private static bool IsEmptyLayout(Layout? layout)
556+
{
557+
return layout is null || ReferenceEquals(layout, Layout.Empty);
558+
}
559+
530560
/// <summary>
531561
/// Create key for grouping. Needed for multiple events in one mail message
532562
/// </summary>
@@ -653,8 +683,9 @@ internal static MessagePriority ParseMessagePriority(string priority)
653683
/// <param name="mailAddressCollection">Addresses appended to this list</param>
654684
/// <param name="layout">layout with addresses, ; separated</param>
655685
/// <param name="logEvent">event for rendering the <paramref name="layout" /></param>
686+
/// <param name="allowThrow">Abort early when invalid email address format</param>
656687
/// <returns>added a address?</returns>
657-
private bool AddAddresses(InternetAddressList mailAddressCollection, Layout? layout, LogEventInfo logEvent)
688+
private bool AddAddresses(InternetAddressList mailAddressCollection, Layout? layout, LogEventInfo logEvent, bool allowThrow = false)
658689
{
659690
var added = false;
660691
var mailAddresses = RenderLogEvent(layout, logEvent);
@@ -667,7 +698,16 @@ private bool AddAddresses(InternetAddressList mailAddressCollection, Layout? lay
667698
if (string.IsNullOrEmpty(mailAddress))
668699
continue;
669700

670-
mailAddressCollection.Add(MailboxAddress.Parse(mail));
701+
try
702+
{
703+
mailAddressCollection.Add(MailboxAddress.Parse(mail));
704+
}
705+
catch (Exception ex)
706+
{
707+
InternalLogger.Error(ex, "{0}: Invalid email address: {1}", this, mailAddress);
708+
if (allowThrow || LogManager.ThrowExceptions)
709+
throw;
710+
}
671711
added = true;
672712
}
673713
}

test/NLog.MailKit.Tests/UnitTests/MailTargetTests.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,46 @@ public void MailTarget_WithEmptyTo_ThrowsConfigException()
5252
);
5353
}
5454

55+
[Fact]
56+
public void MailTarget_WithBlankTo_ThrowsConfigException()
57+
{
58+
var mmt = new MailTarget
59+
{
60+
From = "foo@bar.com",
61+
To = " ",
62+
Subject = "Hello from NLog",
63+
SmtpServer = "server1",
64+
SmtpPort = 27,
65+
};
66+
67+
Assert.Throws<NLogConfigurationException>(() =>
68+
new LogFactory().Setup().LoadConfiguration(cfg =>
69+
{
70+
cfg.Configuration.AddRuleForAllLevels(mmt);
71+
})
72+
);
73+
}
74+
75+
[Fact]
76+
public void MailTarget_WithInvalidTo_ThrowsConfigException()
77+
{
78+
var mmt = new MailTarget
79+
{
80+
From = "foo@bar.com",
81+
To = "@",
82+
Subject = "Hello from NLog",
83+
SmtpServer = "server1",
84+
SmtpPort = 27,
85+
};
86+
87+
Assert.Throws<NLogConfigurationException>(() =>
88+
new LogFactory().Setup().LoadConfiguration(cfg =>
89+
{
90+
cfg.Configuration.AddRuleForAllLevels(mmt);
91+
})
92+
);
93+
}
94+
5595
[Fact]
5696
public void MailTarget_WithEmptyFrom_ThrowsConfigException()
5797
{

0 commit comments

Comments
 (0)