Log4net’s SmtpAppender with multiple email addresses

Log4net is a popular logging framework, and amongst the various logging “appenders” it includes one for sending emails – the SmtpAppender. The documentation for the SmtpAppender’s To property says it contains a semicolon-delimited list of email addresses.

However if you try to do that, you won’t see any emails being sent. Add the following to your app.config file to enable log4net’s debug logging:

  <appSettings>
    <add key="log4net.Internal.Debug" value="true" />
  </appSettings>
  
 <system.diagnostics>
  <trace autoflush="true">
   <listeners>
    <add name="textWriterTraceListener" 
     type="System.Diagnostics.TextWriterTraceListener"
     initializeData="C:\\tmp\\log4net.txt" />
    </listeners>
   </trace>
 </system.diagnostics>

You’ll then see this internal error message in the log4net.txt file:

System.FormatException: The specified string is not in the form required for an e-mail address.
   at System.Net.Mime.MailBnfHelper.ReadMailAddress(String data, Int32& offset, String& displayName)
   at System.Net.Mail.MailAddressCollection.ParseValue(String addresses)
   at log4net.Appender.SmtpAppender.SendEmail(String messageBody)
   at log4net.Appender.SmtpAppender.SendBuffer(LoggingEvent[] events)

This shows that the SmtpAppender is leveraging the .NET Framework’s System.Net.Mail.MailAddressCollection class. The ParseValue method is not public, but Add(string) is, and if you scroll down to the remarks, you’ll see the following text:

If multiple e-mail addresses separated with a semicolon character (";") are passed in the addresses parameter. a FormatException exception is raised.

So it turns out log4net’s documentation is misleading, or at least out of date. Change your email addresses to use the comma and everything comes good again.

Written on November 24, 2008