square
square

Reputation: 123

How to send colorful mail in nlog

below config was my nlog setting, this setting send mail is OK .

<target name="mail" xsi:type="Mail"
            smtpServer="SMTP SERVER"
            smtpPort="25"
            smtpAuthentication="None"   
            enableSsl="false"   
            from="email address"  
            to="email address"
            html="true"
            encoding="UTF-8"
            addNewLines="true"
            replaceNewlineWithBrTagInHtml ="true"
            subject="SYSTEM MESSAGE:${machinename} 於 ${shortdate} ${time} create ${level} message "
            header="========================================================================="
            body="${newline} 
            time:${longdate} ${newline}${newline}
            Log level:${level:uppercase=true} ${newline}${newline}
            Logger:${logger} ${newline}${newline}
            Source:${callsite:className=true} ${newline}${newline}
            Exception:${exception:format=type} ${newline}${newline}
            Error message:${message} ${newline}${newline}"     
            footer="========================================================================="
    />

</targets>

 <rules>
    <logger name="*" minlevel="Fatal" writeTo="mail" />
 </rules>

but I want to send colorful mail. How to setting configure ?

Upvotes: 9

Views: 2420

Answers (2)

OfirD
OfirD

Reputation: 10490

An easy approach is to log messages with the HTML already in the logged string, for example:

In the config file:

<targets>
   <target 
      name="mail" 
      xsi:type="Mail" 
      replaceNewlineWithBrTagInHtml="true"
      html="true"
      body="${message}"             
   />
</targets>
<rules>
    <logger name="*" minlevel="Info" writeTo="mail"></logger>
</rules>

In the code:

log.Info("<strong>My Bolded Message</string>");

Also, instead of inlining the HTML tags, one can use an HTML library like htmltags or even System.Xml.Linq to make it much more robust.

Upvotes: -1

Julian
Julian

Reputation: 36770

For markup like colors in your e-mail, you need a html mail and CSS styling.

e.g. this html:

<body>
    <b style="color:red">Bold and red text</b>
</body>

You need to set the html option on the mail target to true and in your nlog.config you need to XML encode the html, so in result:

<target name="mail" xsi:type="Mail"
            html="true"
            ...

            body="&lt;body&gt;
&lt;b style=&quot;color:red&quot;&gt;Bold and red text&lt;/b&gt;
&lt;/body&gt;"
    />

Please note that not all CSS is supported in all email clients. See CSS Support Guide for Email Clients

Upvotes: 3

Related Questions