c# - 使用 .NET Core 2.2 发送电子邮件

标签 c# sendmail asp.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"
}

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

enter image description here

最佳答案

您可以在电子邮件发件人中将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.启动ConfigureServices

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();
    }
}

4.无论您需要什么地方,都可以通过 DI 使用 Options 访问 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;
    }
}

关于c# - 使用 .NET Core 2.2 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58730594/

相关文章:

c# - 使用(C#、mpr.dll)访问网络驱动器文件时出错 : Unable to load DLL 'mrp.dll'

asp.net-mvc-4 - 使用 SmtpClient 的 MVC 4.5 : Send an email with . pdf 附件 - 我在这里缺少什么?

amazon-ec2 - EC2 - 全新 PHP 安装 - 邮件无法正常工作

email - 无法从 liferay Hook 发送邮件

c# - 为什么 Point.Offset() 没有在只读结构中给出编译器错误?

c# - 为什么 log4net 在配置之前创建一个空日志文件?

c# - 如何在 C#/ASP.NET MVC 中实现搜索功能

asp.net-core - 在 vscode 调试控制台中禁用符号加载的详细日志记录

c# - 如何修复 .net core 2.2 应用程序中找不到的 swagger.json

c# - ASP.Net Core MVC/API/SignalR - 更改身份验证方案(Cookie 和 JWT)