简体   繁体   中英

Sending lots of mails using SmtpClient (C#) takes very long after a while

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?

使用SmtpClient.SendAsync而不是SmtpClient.Send。

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM