serilog / serilog-sinks-email

A Serilog sink that writes events to SMTP email
Apache License 2.0
76 stars 69 forks source link

Receiving HTML email as plain text #116

Closed DarkEyeDragon closed 11 months ago

DarkEyeDragon commented 1 year ago

Following the example of the HtmlTableFormatter in IBatchFormatter i tried to send an email with html formatting. However it was just received as plain text in Outlook 2021:

<table><tr>Source directory not found: (path to file)</tr><tr>Source directory not found:  (path to file)</tr><tr>Source directory not found:  (path to file)</tr><tr>Source directory not found:  (path to file)</tr></table>

The following setup was used:

public class HtmlTableFormatter : IBatchTextFormatter
{
    public void Format(LogEvent logEvent, TextWriter output)
    {
        output.Write("&lt;tr&gt;");
        using var buffer = new StringWriter();
        logEvent.RenderMessage(buffer);
        output.Write(WebUtility.HtmlEncode(buffer.ToString()));
        output.Write("&lt;/tr&gt;");
    }

    public void FormatBatch(IEnumerable<LogEvent> logEvents, TextWriter output)
    {
        output.Write("&lt;table&gt;");
        foreach (var logEvent in logEvents)
        {
            Format(logEvent, output);
        }

        output.Write("&lt;/table&gt;");
    }
}
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console().MinimumLevel.Error()
    .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(30), restrictedToMinimumLevel: LogEventLevel.Information)
    .WriteTo.Email(new EmailConnectionInfo
    {
        FromEmail = "redacted",
        ToEmail = "redacted",
        MailServer = "smtp.office365.com",
        NetworkCredentials = new NetworkCredential("redacted", "redacted"),
        IsBodyHtml = true,
        EmailSubject = "Sync service - Errors",
    }, new HtmlTableFormatter())
    .MinimumLevel.Error()
    .CreateLogger();
nblumhardt commented 11 months ago

You shouldn't be escaping characters like < etc when writing them through your formatter - this encodes them to display as text, rather than act as markup. A good one for the serilog tag on Stack Overflow if you still need a hand 👍