Click or drag to resize

MailTarget Class

Sends log messages by email using SMTP protocol.
Inheritance Hierarchy
SystemObject
  NLog.TargetsTarget
    NLog.TargetsTargetWithLayout
      NLog.TargetsTargetWithLayoutHeaderAndFooter
        NLog.MailKitMailTarget

Namespace:  NLog.MailKit
Assembly:  NLog.MailKit (in NLog.MailKit.dll) Version: 5.2.0+78fee640bcc81f8f578f417ab1504dd9618e7898
Syntax
public class MailTarget : TargetWithLayoutHeaderAndFooter

The MailTarget type exposes the following members.

Constructors
  NameDescription
Public methodMailTarget
Initializes a new instance of the MailTarget class.
Public methodMailTarget(String)
Initializes a new instance of the MailTarget class.
Top
Properties
  NameDescription
Public propertyAddNewLines
Gets or sets a value indicating whether to add new lines between log entries.
Public propertyBcc
Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
Public propertyBody
Gets or sets mail message body (repeated for each log message send in one mail).
Public propertyCc
Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
Public propertyEnableSsl
Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. See also SecureSocketOption
Public propertyEncoding
Gets or sets encoding to be used for sending e-mail.
Public propertyFooter
Gets or sets the footer.
(Inherited from TargetWithLayoutHeaderAndFooter.)
Public propertyFrom
Gets or sets sender's email address (e.g. joe@domain.com).
Public propertyHeader
Gets or sets the header.
(Inherited from TargetWithLayoutHeaderAndFooter.)
Public propertyHtml
Gets or sets a value indicating whether to send message as HTML instead of plain text.
Protected propertyIsInitialized
Gets a value indicating whether the target has been initialized.
(Inherited from Target.)
Public propertyLayout
Gets or sets the text to be rendered.
(Inherited from TargetWithLayoutHeaderAndFooter.)
Protected propertyLoggingConfiguration
Gets the logging configuration this target is part of.
(Inherited from Target.)
Public propertyMailHeaders
Gets the array of email headers that are transmitted with this email message
Public propertyName
Gets or sets the name of the target.
(Inherited from Target.)
Public propertyPickupDirectoryLocation
Gets or sets the folder where applications save mail messages to be processed by the local SMTP server.
Public propertyPriority
Gets or sets the priority used for sending mails.
Public propertyReplaceNewlineWithBrTagInHtml
Gets or sets a value indicating whether NewLine characters in the body should be replaced with
tags.
Public propertySecureSocketOption
Provides a way of specifying the SSL and/or TLS encryption If EnableSsl is true, then SslOnConnect will be used.
Public propertySkipCertificateValidation
Gets or sets a value indicating whether SmtpClient should ignore invalid certificate.
Public propertySmtpAuthentication
Gets or sets SMTP Authentication mode.
Public propertySmtpPassword
Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic").
Public propertySmtpPort
Gets or sets the port number that SMTP Server is listening on.
Public propertySmtpServer
Gets or sets SMTP Server to be used for sending.
Public propertySmtpUserName
Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic").
Public propertySubject
Gets or sets the mail subject.
Protected propertySyncRoot
Gets the object which can be used to synchronize asynchronous operations that must rely on the .
(Inherited from Target.)
Public propertyTimeout
Gets or sets a value indicating the SMTP client timeout (in milliseconds)
Public propertyTo
Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
Top
Methods
  NameDescription
Protected methodCloseTarget
Closes the target to release any initialized resources
(Inherited from Target.)
Public methodDispose
Closes the target.
(Inherited from Target.)
Protected methodDispose(Boolean)
Releases unmanaged and - optionally - managed resources.
(Inherited from Target.)
Public methodFlush
Flush any pending log messages (in case of asynchronous targets).
(Inherited from Target.)
Protected methodFlushAsync
Flush any pending log messages
(Inherited from Target.)
Protected methodInitializeTarget
Initializes the target before writing starts
(Overrides TargetInitializeTarget.)
Public methodPrecalculateVolatileLayouts
Calls the Precalculate(LogEventInfo) on each volatile layout used by this target. This method won't prerender if all layouts in this target are thread-agnostic.
(Inherited from Target.)
Protected methodRenderLogEvent(Layout, LogEventInfo)
Renders the logevent into a string-result using the provided layout
(Inherited from Target.)
Protected methodRenderLogEventT(LayoutT, LogEventInfo, T)
Renders the logevent into a result-value by using the provided layout
(Inherited from Target.)
Protected methodResolveServiceT
Resolve from DI ServiceRepository
(Inherited from Target.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Target.)
Protected methodWrite(AsyncLogEventInfo)
Writes async log event to the log target.
(Overrides TargetWrite(AsyncLogEventInfo).)
Protected methodWrite(IListAsyncLogEventInfo)
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.
(Overrides TargetWrite(IListAsyncLogEventInfo).)
Protected methodWrite(LogEventInfo)
Writes logging event to the target destination
(Inherited from Target.)
Public methodWriteAsyncLogEvent
Writes the log to the target.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(AsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(IListAsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Protected methodWriteAsyncThreadSafe(AsyncLogEventInfo)
Writes a log event to the log target, in a thread safe manner. Any override of this method has to provide their own synchronization mechanism. !WARNING! Custom targets should only override this method if able to provide their own synchronization mechanism. Layout-objects are not guaranteed to be thread-safe, so using them without a SyncRoot-object can be dangerous.
(Inherited from Target.)
Protected methodWriteAsyncThreadSafe(IListAsyncLogEventInfo)
Writes an array of logging events to the log target, in a thread safe manner. Any override of this method has to provide their own synchronization mechanism. !WARNING! Custom targets should only override this method if able to provide their own synchronization mechanism. Layout-objects are not guaranteed to be thread-safe, so using them without a SyncRoot-object can be dangerous.
(Inherited from Target.)
Protected methodWriteFailedNotInitialized
LogEvent is written to target, but target failed to successfully initialize
(Inherited from Target.)
Top
Remarks
Examples

To set up the target in the configuration file, use the following syntax:

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <target name="mail" xsi:type="Mail"
 7            smtpServer="192.168.0.15" 
 8            from="jaak@jkowalski.net"
 9            to="jaak@jkowalski.net"
10            subject="test subject" />
11    </targets>
12
13    <rules>
14        <logger name="*" minlevel="Debug" writeTo="mail" />
15    </rules>
16</nlog>

To set up the log target programmatically use code like this:

C#
 1using System;
 2
 3using NLog;
 4using NLog.Targets;
 5
 6class Example
 7{
 8    static void Main(string[] args)
 9    {
10        try
11        {
12            Console.WriteLine("Setting up the target...");
13            MailTarget target = new MailTarget();
14
15            target.SmtpServer = "192.168.0.15";
16            target.From = "jaak@jkowalski.net";
17            target.To = "jaak@jkowalski.net";
18            target.Subject = "sample subject";
19
20            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
21
22            Console.WriteLine("Sending...");
23            Logger logger = LogManager.GetLogger("Example");
24            Console.WriteLine("Sent.");
25            logger.Debug("log message");
26        }
27        catch (Exception ex)
28        {
29            Console.WriteLine("EX: {0}", ex);
30
31        }
32    }
33}

Mail target works best when used with BufferingWrapper target which lets you send multiple log messages in single mail

To set up the buffered mail target in the configuration file, use the following syntax:

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <targets>
 6        <target name="mail" xsi:type="BufferingWrapper" bufferSize="5">
 7            <target xsi:type="Mail"
 8                smtpServer="192.168.0.15" 
 9                from="jaak@jkowalski.net"
10                to="jaak@jkowalski.net"
11                subject="test subject" />
12        </target>
13    </targets>
14
15    <rules>
16        <logger name="*" minlevel="Debug" writeTo="mail" />
17    </rules>
18</nlog>

To set up the buffered mail target programmatically use code like this:

C#
 1using System;
 2
 3using NLog;
 4using NLog.Targets;
 5using NLog.Targets.Wrappers;
 6
 7class Example
 8{
 9    static void Main(string[] args)
10    {
11        try
12        {
13            NLog.Internal.InternalLogger.LogToConsole = true;
14            NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace;
15            Console.WriteLine("Setting up the target...");
16            MailTarget target = new MailTarget();
17
18            target.SmtpServer = "192.168.0.15";
19            target.From = "jaak@jkowalski.net";
20            target.To = "jaak@jkowalski.net";
21            target.Subject = "sample subject";
22            target.Body = "${message}${newline}";
23
24            BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5);
25
26            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug);
27
28            Console.WriteLine("Sending...");
29            Logger logger = LogManager.GetLogger("Example");
30            logger.Debug("log message 1");
31            logger.Debug("log message 2");
32            logger.Debug("log message 3");
33            logger.Debug("log message 4");
34            logger.Debug("log message 5");
35            logger.Debug("log message 6");
36            logger.Debug("log message 7");
37            logger.Debug("log message 8");
38
39            // this should send 2 mails - one with messages 1..5, the other with messages 6..8
40            Console.WriteLine("Sent.");
41        }
42        catch (Exception ex)
43        {
44            Console.WriteLine("EX: {0}", ex);
45
46        }
47    }
48}
See Also