【问题标题】:Can mailkit in ASP.NET read a config file?ASP.NET 中的 mailkit 可以读取配置文件吗?
【发布时间】:2022-01-07 14:51:50
【问题描述】:

我正在尝试在 ASP.NET core 3.1 中构建一个用于管理公司客户的网络应用程序。当用户在数据库中保存新客户端时,我希望应用向客户端发送欢迎邮件。

我尝试使用 SmtpClient class 这样做,但微软本身似乎不鼓励这样做:

很重要。我们不建议您将 SmtpClient 类用于新开发,因为 SmtpClient 不支持许多现代协议。请改用MailKit 或其他库。

所以我决定使用MailKit library,到目前为止我已经编写了这个代码:

// Send a welcome email.
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("CompanyName", "email"));
message.To.Add(MailboxAddress.Parse(obj.Email));
message.Subject = "Welcome mail";
message.Body = new TextPart("plain")
    {
        Text = @"Welcome " + obj.Name + "!"
    };
SmtpClient client = new SmtpClient();
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("mail", "password");
client.Send(message);
client.Disconnect(true);
client.Dispose();

请注意,上面的代码段是在处理存储新客户端的控制器中编写的。在验证并保存数据库更改后,我立即发送电子邮件。

这很好用,但我想看看是否可以从 app 文件夹中的配置文件中读取所有内容,例如邮件地址、密码、smtp 客户端、端口等,而不是很难-编码。我认为 MailKit 无法读取 web.config 文件,我还能做些什么吗?任何帮助将不胜感激!

【问题讨论】:

  • 没有什么能阻止您编写可以将其提供给 MailKit 的代码。
  • 虽然@TheFloods 的答案是正确的,但如果您想在运行时更改邮件设置,您应该考虑IOptionsSnapshot(瞬态)或IOptionsMonitor(单例)。 Docs

标签: c# asp.net-core mailkit


【解决方案1】:

是的,你可以!

在你的 Startup.cs 中:

services.Configure<EmailSettings>(Configuration.GetSection("EmailSection"));

创建配置类 EmailSettings :

public class EmailSettings
{
    public string Smtp { get; set; }
    public string SendFrom { get; set; }
    public string Password { get; set; }
    public int Port { get; set; }
}

然后将其添加到您的 appsettings.json 中:

...
"EmailSection": {
   "Smtp": "smtp.gmail.com",
   "SendFrom": "noreply@domain.com",
   "Password": "123456789",
   "Port": 465
 },
 ...

最后,您可以使用依赖注入从控制器或任何您想要的调用配置类 EmailSettings :

public class HomeController : Controller
{
   private EmailSettings _emailSettings;
   // Constructor of controller
   public HomeController : Controller (IOptions<EmailSettings> emailSettings)
   {
      _emailSettings = emailSettings.Value;
   }
   
   public IActionResult Index()
   {
      string getSmtp = _emailSettings.Smtp;
      string getPassword = _emailSettings.Password;
      // ...
   }
}

【讨论】:

  • 谢谢!您的代码非常简单易懂!我想指出,我所做的唯一更改是在构造函数中:_emailSettings = emailSettings.Value;否则,我会收到“无法将类型 'Microsoft.Extensions.Options.IOptions 隐式转换为 ...”错误。
  • 没问题。你是对的,我在上面编辑了代码:'_emailSettings = emailSettings.Value;'
猜你喜欢
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 2017-01-15
  • 2013-01-04
  • 2012-06-18
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
相关资源
最近更新 更多