Sending mail with task parallel library throws error

余生颓废 提交于 2019-12-01 00:45:56

Regarding the exception 'net_io_connectionclosed', please look at this link as it might point you in the right direction about why the connection is being closed. It could be authentication problems, firewall etc.

Enabling Tracing for System.Net

Please find below the code that I would use in your situation instead of spawning 1000 tasks which is not very efficient.

Sending bulk emails with Tasks Parallel.ForEach

As Jim mentions, you're likely just hitting a throttling/rejection situation. IMHO, you're likely to be more successful by 1) using a single SmtpClient rather than N of them (so the single client could internally serialize as/if necessary) and 2) using the built-in async call (SendMailAsync) instead of StartNew and calling the sync version.

Something like:

var messages = ... // get collection of MailMessage instances
var smtpClient = new SmtpClient { ... }; // construct a single SmtpClient
var tasks = messages.Select(smtpClient.SendMailAsync).ToArray();
Task.WaitAll(tasks);

I'm not sure if that's really going to help much, though - if it still fails, you might just need to make a single long-running Task that sends the emails serially.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!