你可以使用Options
在您的电子邮件发件人中添加 DI,请参阅
https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-implementation https://kenhaggerty.com/articles/article/aspnet-core-22-smtp-emailsender-implementation
1.appsettings.json
"Smtp": {
"Server": "smtp.MyHost.com",
"Port": 25,
"FromAddress": "MyEmailAddress"
}
2.Smtp设置.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();
}
}
4.使用访问SmtpSettingsOptions
无论您需要什么,都可以通过 DI 进行。
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;
}
}