我們在項目中經常會有報警通知,業務通知使用者的場景,通知的手段有短信、電話、群通知、郵件通知等。其中郵件通知是比較常見的場景,比如登入驗證碼,找回賬戶驗證碼,綁定郵箱,又或者是審批通知、會議通知等等。
實作的思路:
1.首先系統中會維護一個系統郵箱賬戶密碼,關于系統中的通知全由該賬戶進行發送。
2.建立郵件任務表以及郵件日志表,當業務端有發郵件需求時,往郵件任務表中插入任務資料,記錄标題、内容、收件人等資訊。
3.郵件任務執行服務,根據任務表中的資料進行任務執行,執行結束對任務狀态進行标記,執行失敗則進行延遲再次執行,直到執行重試次數結束 進行執行失敗标記。執行結束進行日志記錄。
MailKit 是C#郵件推送常用的庫,可在NUGET上進行安裝使用。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLkVGM5EmNzcDM5UDZiN2MhZWM5QTYiZWZlJDO3YDNjZzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
/// <summary>
/// 發送郵件
/// </summary>
/// <param name="mailBodyEntity">郵件基礎資訊</param>
/// <param name="sendServerConfiguration">發件人基礎資訊</param>
public static SendResultEntity SendMail(MailBodyEntity mailBodyEntity,
SendServerConfigurationEntity sendServerConfiguration)
{
if (mailBodyEntity == null)
{
throw new ArgumentNullException();
}
if (sendServerConfiguration == null)
{
throw new ArgumentNullException();
}
var sendResultEntity = new SendResultEntity();
using (var client = new SmtpClient(new ProtocolLogger(MailMessage.CreateMailLog())))
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
Connection(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
SmtpClientBaseMessage(client);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
Authenticate(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
Send(mailBodyEntity, sendServerConfiguration, client, sendResultEntity);
if (sendResultEntity.ResultStatus == false)
{
return sendResultEntity;
}
client.Disconnect(true);
}
return sendResultEntity;
}