首页 > 解决方案 > 使用 .NET Core 2.2 发送电子邮件

问题描述

在 MVC ASP.NET 中,您可以像这样在 web.config 文件中设置 smtp 配置:

<system.net>
    <mailSettings>
        <smtp from="MyEmailAddress" deliveryMethod="Network">
            <network host="smtp.MyHost.com" port="25" />
        </smtp>
    </mailSettings>
</system.net>

这非常有效。

但我无法让它在 .NET Core 2.2 中工作,因为你有一个 appsettings.json 文件。

我有这个 :

"Smtp": {
    "Server": "smtp.MyHost.com",
    "Port": 25,
    "FromAddress": "MyEmailAddress"
}

发送邮件时显示此错误消息:

在此处输入图像描述

标签: c#sendmailasp.net-core-2.2

解决方案


您可以Options在您的电子邮件发件人中使用 DI,请参阅

https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-implementation

1.appsettings.json

"Smtp": {
    "Server": "smtp.MyHost.com",
    "Port": 25,
    "FromAddress": "MyEmailAddress"
}

2.SmtpSettings.cs

public class SmtpSettings
{
    public string Server { get; set; }
    public int Port { get; set; }
    public string FromAddress { get; set; }
}

3.启动配置服务

public class Startup
{
    IConfiguration Configuration;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<SmtpSettings>(Configuration.GetSection("Smtp"));
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }
}

Options 4.在任何需要的地方使用 DI访问 SmtpSettings 。

public class EmailSender : IEmailSender
{
    private readonly SmtpSettings _smtpSettings;

    public EmailSender(IOptions<SmtpSettings> smtpSettings)
    {
        _smtpSettings = smtpSettings.Value;

    }
    public Task SendEmailAsync(string email, string subject, string message)
    {
        var from = _smtpSettings.FromAddress;
        //other logic
        using (var client = new SmtpClient())
        {
            {
                await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);
            }
        }
        return Task.CompletedTask;
    }
}

推荐阅读