NET Core Mailkit无法发送多封电子邮件

问题描述

我正在使用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,toEmail2,html);
}

函数正在等待一分钟,然后在此行出现错误smtp.Connect("smtp.office365.com",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",SecureSocketoptions.Auto);一个SendEmail(发送到Email1)有效,但是第二个(发送到Email2)与使用 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,toEmail2,html);

    smtp.Disconnect(true);
}