使用.NET Core 2.2发送电子邮件 [英] Send email with .NET Core 2.2
问题描述
在MVC ASP.NET中,您可以像这样在web.config文件中设置smtp配置:
In MVC ASP.NET you can set the smtp configuration in the web.config file like this :
<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文件.
But I can't get it to work in .NET Core 2.2 because there you have a appsettings.json file.
我有这个:
"Smtp": {
"Server": "smtp.MyHost.com",
"Port": 25,
"FromAddress": "MyEmailAddress"
}
发送邮件时会显示此错误消息:
When sending a mail it shows this error message :
推荐答案
您可以在电子邮件发件人中将Options
与DI一起使用,请参阅
You could use Options
with DI in your email sender,refer to
https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-实现
1.appsettings.json
1.appsettings.json
"Smtp": {
"Server": "smtp.MyHost.com",
"Port": 25,
"FromAddress": "MyEmailAddress"
}
2.SmtpSettings.cs
2.SmtpSettings.cs
public class SmtpSettings
{
public string Server { get; set; }
public int Port { get; set; }
public string FromAddress { get; set; }
}
3.Startup ConfigureServices
3.Startup 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.
4.Access the SmtpSettings using Options
by DI wherever you need.
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;
}
}
这篇关于使用.NET Core 2.2发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!