Reputation: 944
I am using SmtpClient.SendAsync
(C#) to send emails in ASP.NET web applications and services. The web application/service runs on Windows Server 2012 R2 using IIS 8.
There are times where the call to SendAsync
hangs up and does not appear to send the mail message asynchronously, so the calling thread blocks. This behavior seems to be sporadic. I cannot replicate the problem in a testing environment. This is especially problematic when sending the email as a result of a call to a web method because the timeout is 60 seconds (I'm using SendAsync
for this very reason so the client doesn't experience any time delay).
Here is my code snippet.
SmtpClient client;
MailMessage msg;
public void SendMail()
{
try
{
client = new SmtpClient("[email protected]");
msg = new MailMessage();
msg.Subject = "Test";
msg.Body = "This is the body";
msg.From = "[email protected]";
msg.To.Add("[email protected]");
client.SendCompleted += new SendCompletedEventHandler(sendCompletedCallback);
client.SendAsync(msg, "Test");
}
catch (Exception ex)
{
// Log error
}
}
private void sendCompletedCallback(object send, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
// Log error
}
else if (e.Cancelled)
{
// Log cancellation
}
else
{
// Log success
}
client.Dispose();
msg.Dispose();
}
Why does the call to SendAsync
hang and block the calling thread at times?
Upvotes: 3
Views: 1981
Reputation: 1107
Please check below link, https://msdn.microsoft.com/en-us/library/x5x13z6h(v=vs.110).aspx There might be two case, either it is not waiting for e-mail transmission to complete before attempting to send another e-mail message or recipients is invalid
Upvotes: 1