使用 MailKit 处理一长串电子邮件

问题描述

我们目前使用 SmtpClient 发送电子邮件,我们通常每天大约有 1000-5000 封电子邮件。我们遇到了一些性能问题,有时发送命令需要很长时间。经过研究,我了解了 MailKit 以及它如何取代 SmtpClient。通读示例,每一个都需要

            using (var client = new SmtpClient ()) {
            client.Connect ("smtp.friends.com",587,false);

            // Note: only needed if the SMTP server requires authentication
            client.Authenticate ("joey","password");

            client.Send (message);
            client.disconnect (true);
            }

在每条消息后断开连接。如果我打算按顺序发送许多消息,我是否仍然应该为每个消息调用一个新的 SmtpClient 实例并断开它?处理一长串电子邮件发送的正确方法是什么?

解决方法

您不需要在发送一条消息后断开连接。您可以反复调用 Send() 方法,直到完成发送消息。

一个简单的例子可能如下所示:

static void SendALotOfMessages (MimeMessage[] messages)
{
    using (var client = new SmtpClient ()) {
        client.Connect ("smtp.friends.com",587,false);

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate ("joey","password");

        // send a lot of messages...
        foreach (var message in messages)
            client.Send (message);

        client.Disconnect (true);
    }
}

一个更复杂的例子会考虑对 SmtpProtocolExceptionIOException 的处理,这通常意味着客户端断开连接。

如果您收到 SmtpProtocolExceptionIOException,则保证您需要重新连接。这些异常总是致命的。

另一方面,

SmtpCommandException 通常不是致命的,您通常不需要重新连接。您可以随时检查 SmtpClient.IsConnected 属性进行验证。