簡體   English   中英

NET Core Mailkit 無法發送多封電子郵件

[英]NET Core Mailkit Cannot send multiple email

我正在使用 MailKit 在 .NET Core 3.1 項目中發送電子郵件。

public void SendEmail(string fromEmail, string fromEmailPassword, string toEmail, string subject, string html)
{
    var email = new MimeMessage();
    email.Sender = MailboxAddress.Parse(fromEmail);
    email.To.Add(MailboxAddress.Parse(toEmail));
    email.Subject = subject;
    email.Body = new TextPart(TextFormat.Html) { Text = html };

    using var smtp = new SmtpClient();
    smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
    smtp.Authenticate(fromEmail, fromEmailPassword);
    smtp.Send(email);            
    smtp.Disconnect(true);
}

public void SendEmail()
{
    ...
    SendEmail(fromEmail, fromEmailPassword, toEmail1, subject, html);
    SendEmail(fromEmail, fromEmailPassword, toEmail2, subject, html);
}

該函數等待一分鍾,然后在這一行出現錯誤: smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);

2020-10-15 15:20:31.457 +07:00 [Error] An unhandled exception has occurred while executing the request.
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

This usually means that the SSL certificate presented by the server is not trusted by the system for one or more 
of the following reasons:

1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.

然后我將 SecureSocketOptions 更改為 SecureSocketOptions.Auto: smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.Auto); 第一個 SendEmail (send toEmail1) 工作,但第二個 (send toEmail2) 得到與使用SecureSocketOptions.StartTls時相同的錯誤。 然后我再次運行該函數,第一個 SendEmail 也出現了同樣的錯誤。 我等了幾分鍾再次運行該功能,第一個 SendEmail 工作,第二個電子郵件出錯。

有人可以提出解決方案嗎?

謝謝你。

您面臨的問題是 SMTP 服務器不喜歡您如此快速地連接和重新連接。

您需要做的是重新使用同一個 SmtpClient 連接來發送多條消息,如下所示:

public void SendEmail(SmtpClient smtp, string fromEmail, string toEmail, string subject, string html)
{
    var email = new MimeMessage();
    email.Sender = MailboxAddress.Parse(fromEmail);
    email.To.Add(MailboxAddress.Parse(toEmail));
    email.Subject = subject;
    email.Body = new TextPart(TextFormat.Html) { Text = html };

    smtp.Send(email);
}

public void SendEmail()
{
    using var smtp = new SmtpClient();
    smtp.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
    smtp.Authenticate(fromEmail, fromEmailPassword);

    SendEmail(smtp, fromEmail, toEmail1, subject, html);
    SendEmail(smtp, fromEmail, toEmail2, subject, html);

    smtp.Disconnect(true);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM