Skip to content

Codepolice

  • ⤫

Using log4net to Send Mail With SmtpAppender In a Console Application

Posted by Judy Alvarez Posted on February 28, 2022March 1, 2022
0

I recently built some console apps to do some testing on my server. I wanted to be able to run the apps and get them to print info to the console. I also wanted it to log to a text file and to send e-mails to me. Log4net was the perfect tool to get this done.

This is how my .config files look with log4net. Of course, you have to reference log4net and so on also, use NuGet!

<configuration>
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />
</configSections>
[..]
<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
      <file value="webcontent-logfile.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message% - %level%newline" />
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender, log4net">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="INFO" />
        <foreColor value="White" />
      </mapping>
      <mapping>
        <level value="DEBUG" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level - %message% - %newline" />
      </layout>
    </appender>
    <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
      <!-- The SmtpAppender authenticates against the mail server, the buffersize of 10 provides 10 lines of context when an error happens. -->
      <subject value="Log: Web Content Server Report" />
      <to value="[email protected]" />
      <from value="[email protected]" />
      <smtpHost value="localhost" />
      <bufferSize value="100000" />
      <lossy value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level - %message% - %newline" />
      </layout>
    </appender>
    <root>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="ColoredConsoleAppender"/>
      <appender-ref ref="EmailAppender"/>
    </root>
</log4net>
</configuration>

In the application, I just init log4net like this.

log4net.Config.XmlConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Program));

I saw loads of examples where they used the “BasicConfigurator” instead of the “XmlConfigurator” for some reason but that did not work if I wanted to use the appenders specified in the .config files.

Anyway, since my console app is just running and then quits I had some problems with the SmtpAppender. I guessed I didn’t have time to send the mail before I exited the app but I found some code to solve this as well. Add this at the end of the app and you should be fine.

ILoggerRepository rep = LogManager.GetRepository();
foreach (IAppender appender in rep.GetAppenders()) {
    var buffered = appender as BufferingAppenderSkeleton;
    if (buffered != null) {
        buffered.Flush();
    }
}

Another trick is if you want to change the subject of the e-mail sent you can do like this.

ILoggerRepository rep = LogManager.GetRepository();
foreach (IAppender appender in rep.GetAppenders()) {
    if (appender is SmtpAppender) {
        ((SmtpAppender)appender).Subject = "Log: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm") +" Web Content Server Report";
    }
    var buffered = appender as BufferingAppenderSkeleton;
    if (buffered != null) {
        buffered.Flush();
    }
}

Sorry for not linking to the sources of all this code but most is just stolen from various Stack Overflow questions.

Categories: JavascriptTagged: application state in asp net, asp net 4.5, asp net and web development, asp net basics, asp net core documentation, asp net core latest version, asp net core tutorial for beginners, asp net curso, asp net development company india, asp net e commerce, asp net language, asp net logging, asp net page life cycle, asp net requiredfieldvalidator, asp net tutorial for beginners with examples, asp net tutorial pdf, asp net view state, asp net viewstate, asp net vs asp net mvc, asp net web service, asp net with angular, cross page posting in asp net, crystal report in asp net, message box in asp net, n tier architecture in asp net, page event in asp net, pdf asp net, range validator in asp net, uses of asp net, web api in asp net mvc

Post navigation

Previous Previous post: Send E-Mail When a task in Task Scheduler Fails
Next Next post: Request.Files is Empty in a Web Forms Application

Related Posts

  • What’s next for JavaScript frameworks in 2026

    #​770 — January 27, 2026 Read on the Web JavaScript Weekly Introducing LibPDF: PDF Parsing and Generation from TypeScript — LibPDF bills itself as ‘the PDF library TypeScript deserves’ and supports parsing, modifying, signing and generating PDFs with a modern API in Node, Bun, and the browser. GitHub repo. Documenso JavaScript Frameworks – Heading into 2026

    Posted by Posted on January 27, 2026
    0
  • require(esm) now stable in Node 25

    #​608 — January 22, 2026 Read on the Web Node.js 25.4.0 (Current) Released — Another gradual step forward for Node with require(esm) now marked as stable, as well as the module compile cache, along with a variety of other minor tweaks. Joyee Cheung of the Node team has written a thread on Bluesky going deeper

    Posted by Posted on January 22, 2026
    0
  • A big week for jQuery

    #​769 — January 20, 2026 Read on the Web JavaScript Weekly jQuery 4.0 Released — 20 years on from its original release, the ever-popular (in terms of actual usage) library reaches 4.0 with a migration to ES modules (compatible with modern build tools) along with dropping support for IE 10 and older. With jQuery being

    Posted by Posted on January 20, 2026
    0
  • A new guide to configuring Node packages

    #​607 — January 15, 2026 Read on the Web ⚠️ The Node.js January 13, 2026 Security Releases — Originally expected in December, these releases (of Node.js 25.3.0, 24.13.0, 22.22.0, and 20.20.0) finally landed this week, largely due to their complexity and the scope of the vulnerabilities they tackle. More on that in the next item! The Node.js

    Posted by Posted on January 15, 2026
    0
  • Can we ever fix the web dependency mess?

    #​768 — January 13, 2026 Read on the Web JavaScript Weekly Web Dependencies are Broken; Can We Fix Them? — Lea, who has worked at the heart of Web Standards for years, delivers a compelling (and educational) call to action about a problem every JavaScript developer has encountered: why is managing dependencies and introducing them

    Posted by Posted on January 13, 2026
    0
  • The story of how require(esm) became stable

    #​606 — January 8, 2026 Read on the Web 🎉 Happy New Year! Also, a quick reminder that Node Weekly is now sent every Thursday as part of a reshuffle for many of our newsletters. __Your editor, Peter Cooper npm to Implement ‘Staged Publishing’ After Turbulent Shift Off Classic Tokens — 2025 was a tricky year

    Posted by Posted on January 8, 2026
    0
Judy Alvarez

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Codepolice

  • Github
  • Atlassian
  • Flatlogic
  • Xero
  • Jetbrains
  • Figma
  • What’s next for JavaScript frameworks in 2026
  • require(esm) now stable in Node 25
  • A big week for jQuery
  • A new guide to configuring Node packages
  • Can we ever fix the web dependency mess?
https://flatlogic.com/generator
COPYRIGHT © 2026 - Codepolice