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?