我正在嘗試在 ASP.NET core 3.1 中構建一個 Web 應用程式來管理公司的客戶。當用戶在資料庫中保存新客戶端時,我希望應用程式向客戶端發送歡迎郵件。
我嘗試使用SmtpClient 類來做到這一點,但微軟本身似乎不鼓勵這樣做:
重要的。我們不建議您將 SmtpClient 類用于新開發,因為 SmtpClient 不支持許多現代協議。請改用MailKit或其他庫。
所以我決定使用MailKit 庫,到目前為止我已經撰寫了這個代碼:
// 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 檔案,我還能做些什么嗎?任何幫助,將不勝感激!
uj5u.com熱心網友回復:
是的你可以!
在你 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": "[email protected]",
"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;
// ...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404863.html
標籤:
