Search code examples
c#performancesmtpclientbcc

C# SmtpClient.Send() is slow because of BCC


I'm using "System.Net.Mail" for send email on our Intranet system in C#

The Send() method was very slow and I did not understand why.

After debugging, I've remove the BCC call : (MM is a MailMessage() and Item, a string email address) :

MM.Bcc.Add(new MailAddress(Item));

Before I comment this line, an email was taking about 30 or 40 seconds. Now, it's about 2 seconds. Why?

Is there an explication about this? I can add "To" and "CC" with no problem of performance. But not "BCC".


Solution

  • I had a similar problem and this drove me crazy trying to figure out what made some emails slow and others quick.

    The first email sent after creating SmtpClient takes 5 seconds. After that, reusing the same SmtpClient, it's about 0.4 seconds if done within 60 seconds of the previous one. After that I think it releases it's connection to the pool.

    However adding a CC that is a duplicate of the To address will always add an additional 5 seconds. Adding a duplicate CC twice will add 10 seconds.

    I didn't check, but I assume the same would be true if duplicates are in the "TO" or "BCC" lists.

    Here's the code to remove duplicates:

    // check and remove duplicates
    for (int x = 0; x < message.To.Count; x++)
    {
        for (int y = message.To.Count - 1; y > x; y--)
        {
            if (message.To[y].Address == message.To[x].Address)
                message.To.RemoveAt(y);
        }
        for (int y = message.CC.Count - 1; y >= 0; y--)
        {
            if (message.CC[y].Address == message.To[x].Address)
                message.CC.RemoveAt(y);
        }
        for (int y = message.Bcc.Count - 1; y >= 0; y--)
        {
            if (message.Bcc[y].Address == message.To[x].Address)
                message.Bcc.RemoveAt(y);
        }
    }
    for (int x = 0; x < message.CC.Count; x++)
    {
        for (int y = message.CC.Count - 1; y > x; y--)
        {
            if (message.CC[y].Address == message.CC[x].Address)
                message.CC.RemoveAt(y);
        }
        for (int y = message.Bcc.Count - 1; y >= 0; y--)
        {
            if (message.Bcc[y].Address == message.CC[x].Address)
                message.Bcc.RemoveAt(y);
        }
    }
    for (int x = 0; x < message.Bcc.Count; x++)
    {
        for (int y = message.Bcc.Count - 1; y > x; y--)
        {
            if (message.Bcc[y].Address == message.Bcc[x].Address)
                message.Bcc.RemoveAt(y);
        }
    }