tags:

views:

278

answers:

3

I'm using this piece of code to send a mail:

SmtpClient client = new SmtpClient();
client.Host = smtpServer;
client.Send(mailMessage);

If I trigger this code ten times/second, then after some hundred mails, sending a mail takes 10 seconds... Could there be a queue involved here?

  • Shouldn't this be asynchronous?
+2  A: 

Use SmtpClient.SendAsync rather than SmtpClient.Send.

ho1
+2  A: 

There could be several issues:

Are you properly disposing of your MailMessage objects? If you look, the object implements IDisposable and thus should be disposed of. (I would guess because of the potential attachments.) I would start here.

Have you talked to the server administrator. There could be some sort of throttling mechanism that detects you sending out so many mails in quick succession.

If you want to send you emails asynchronously and care about the result of the attempt to send, then be sure to register for the SendCompleted event. You will also want to store either the message itself or some representation to know which message was completed in the SendCompleted event. Keep in mind that the order things start in may not be the order they complete in.

Kirk
+1  A: 

Could it be the mail server throttling your requests? I send mail using the local IIS smtp server, and "sending" the mail takes very little time for .NET even when I have thousands of messages sent within minutes (exception handler went wrong :P ), but they can be processed very slowly by the IIS, and can take hours sometimes to be cleared in the IIS mail queue

Artiom Chilaru