简体   繁体   English

过一会儿,使用SmtpClient(C#)发送大量邮件

[英]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? 如果我每秒触发此代码十次,那么在发送几百封邮件后,发送邮件将花费10秒钟...这里是否可能有队列?

  • Shouldn't this be asynchronous? 这不应该是异步的吗?

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

There could be several issues: 可能有几个问题:

Are you properly disposing of your MailMessage objects? 您是否正确处理了MailMessage对象? If you look, the object implements IDisposable and thus should be disposed of. 如果您看,该对象实现IDisposable,因此应将其丢弃。 (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. 如果要异步发送电子邮件并关心发送尝试的结果,请确保注册SendCompleted事件。 You will also want to store either the message itself or some representation to know which message was completed in the SendCompleted event. 您还将需要存储消息本身或某种表示形式,以了解在SendCompleted事件中完成了哪条消息。 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 我使用本地IIS smtp服务器发送邮件,即使在几分钟之内发送了数千条消息(异常处理程序出错:P),“发送”邮件也只占用.NET很少的时间,但是它们处理起来很慢IIS,有时可能需要几个小时才能在IIS邮件队列中清除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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