在 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"
}
发送邮件时显示此错误消息:
最佳答案
您可以在电子邮件发件人中将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/