Вы можете использовать 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.Доступ к настройкам Smtp с помощью Options
от 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;
}
}