.Net Core 3.1 設定 NLog 寄信流程

設定 Gmail 發信帳號 安全性

原先只要啟用 低安全性應用程式存取權 即可以 SMTP 發信
但因 2022 年 5 月 30 後 Google 因為安全性問題關閉此功能
所以改以設定應用程式密碼來取得權限

  1. 進入發信帳號的 Google 帳戶 > 安全性 > 兩步驟驗證

  2. 依照步驟 透過 簡訊 or 電話 進行認證

  3. 兩步驟驗證設定成功後, 即可 設定 應用程式密碼

  4. 取得 應用程式密碼 (先複製出來 紀錄)

建立測試專案

建立 .Net Core 3.1 WebAPI 專案做範例

dotnet new webapi -f netcoreapp3.1 -o Nlog_Test

安裝 NLog相關套件

dotnet add package NLog.Web.AspNetCore
dotnet add package NLog.MailKit
dotnet add package NLog.Config

設定 Nlog.config

subject = 標題
to = 收信人
from = 發信人
smtpUserName = 發信帳號
smtpPassword = 可填入剛剛設定的應用程式密碼

<?xml version="1.0" encoding="utf-8" ?>
<nlog
  xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  internalLogLevel="info"
  internalLogFile="C:\Logs\MyWebsite\nlog-internal.txt">

    <extensions>
        <!--enable NLog.Web for ASP.NET Core-->
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <targets async="true">
        <target xsi:type="Mail"
                name="email"
                header="HEADER ${newline}"
                footer="${newline} FOOTER"
                html="true"
                addNewLines="true"
                replaceNewlineWithBrTagInHtml="true"
                subject="Nlog_Test~~"
                to="to@gmail.com"
                from="from@gmail.com"
                smtpAuthentication="Basic"
                smtpServer="smtp.gmail.com"
                smtpPort="587"
                smtpUserName="from@gmail.com"
                smtpPassword="fvtrqbrkdkgslzux"/>
    </targets>
    <rules>
        <logger name="*" minlevel="Error" writeTo="email" />
    </rules>
</nlog>

修改 .csproj

設定 Nlog.config 複製到輸出目錄

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NLog.Config" Version="4.7.15" />
    <PackageReference Include="NLog.MailKit" Version="4.1.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
  </ItemGroup>

  <ItemGroup>
    <Content Update="Nlog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
</Project>

修改 program.cs (UseNLog)

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using NLog.Web;

namespace Nlog_Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseNLog();
    }
}

修改 WeatherForecastController.cs (新增一行 Error Log 作範例)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Nlog_Test.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogError("發生錯誤~~~~");

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

測試結果

將服務跑起來

dotnet run 

呼叫 https://localhost:5001/WeatherForecast

即可至信箱確認 Log訊息


轉載請註明來源,若有任何錯誤或表達不清楚的地方,歡迎在下方評論區留言,也可以來信至 leozheng0621@gmail.com
如果文章對您有幫助,歡迎斗內(donate),請我喝杯咖啡

斗內💰

×

歡迎斗內

github