Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmtpClient.SendMailAsync method is hanging when sending a big amount of mails

I am trying to send a lot of emails to using SmtpClient.SendMailAsync method. Here is my test method that I call from the simple console application.

    static void Main(string[] args)
    {

        SendMailsOnebyOneAsync().GetAwaiter().GetResult();

    }


    public static async Task SendMailsOnebyOneAsync()
    {
        for (int i = 0; i < 1000; i++)
        {
            try
            {
                using (SmtpClient sMail = new SmtpClient("XXX"))
                {
                    sMail.DeliveryMethod = SmtpDeliveryMethod.Network;
                    sMail.UseDefaultCredentials = false;
                    sMail.Credentials = null;

                    var fromMailAddress = new MailAddress("XXX");
                    var toMailAddress = new MailAddress("XXX");

                    MailMessage message = new MailMessage(fromMailAddress, toMailAddress)
                    {
                        Subject = "test"
                    };

                    await sMail.SendMailAsync(message);

                    Console.WriteLine("Sent {0}", i);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

Sometimes the method is hanging - it awaits to SendMailAsync which seems stuck and doesn't return.

I see one related question SmtpClient SendMailAsync sometimes never returns . But there is no fix suggested that works for me.

When I tried to use the synchronous method SmtpClient.Send everything is OK and application never hangs.

Does anybody have any idea what is wrong?

like image 555
Inako Avatar asked Oct 16 '22 07:10

Inako


1 Answers

One on my colleague pointed me to the fact that SmtpClient is actually obsolete and Microsoft recommends not to use it.

See the following link.

     ************ Update ***********

I have tried to use MailKit as recommended in the link. The same scenario is working perfectly with MailKit for both non async and async sending.

   **********************************
like image 89
Inako Avatar answered Oct 20 '22 04:10

Inako