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?
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.
**********************************
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With