Search code examples
emailsmtpclientmailkit

Using MailKit for a long queue of emails


We currently use SmtpClient to send emails, we usually have around 1000-5000 emails per day. We are having some performance issues, sometimes the Send command takes a very long time. Upon researching, I learned about MailKit and how it replaced SmtpClient. Reading through examples, every single one calls for

            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);
            }

With Disconnect after every message. If I'm planning to send many messages in sequence, should I still call a new SmtpClient instance for each one and Disconnect it? What is the proper way to handle a long sequence of email sends?


Solution

  • You do not need to disconnect after sending a single message. You can keep calling the Send() method over and over until you are done sending messages.

    A simple example might look like this:

    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);
        }
    }
    

    A more complex example would take into consideration handling of SmtpProtocolException and IOException which typically mean that the client got disconnected.

    If you get an SmtpProtocolException or an IOException, you are guaranteed to need to reconnect. Those exceptions are always fatal.

    SmtpCommandException, on the other hand, is typically not fatal and you will normally not need to reconnect. You can always check the SmtpClient.IsConnected property to verify.