Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Best Method to Send Email (System.Net.Mail has issues)

This seems to be pretty straight forward. I need to send email from some ASP.NET applications. I need to do this consistently without strange errors and without CPU utilization going through the roof. I'm not talking about mass emailing, just occasional emails.

System.Net.Mail appears to be horribly broken. The SmtpClient does not issue the Quit command (it may be because Microsoft(R) is not interested in following specifications), therefore a connection is left open. Therefore, if someone tries to email before that connection finally closes, you can get errors from the SMTP Server about too many connections open. This is a bug that Microsoft(R) is completely uninterested in fixing. See here:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=146711

Also, if you look around some suggest to use this code to solve this problem:

smtpClient.ServicePoint.MaxIdleTime = 1;
smtpClient.ServicePoint.ConnectionLimit = 1;

Ok, yes that does "solve" the problem of connections being left open. However, this consistently, try it on a server if you like, causes the CPU on which the process (in this case w3wp.exe) is running to jump and remain at 100% until your application pool is recycled. For whatever reason, the thread that runs mscorwks.dll!CreateApplicationContext is the culprit.

This has the very nice side effect that if you are running on a web host that frowns on sustained 100% CPU usage, you will get your application pool disabled. So this is not as trivial as some suggest.

So my question is what to do? What I need to do is so simple; however getting those "too many connections open" errors is not acceptable and nor is the 100% CPU usage. I don't want to purchase a third party component, not because I'm cheap, but I buy enough components and MSDN subscription that it seems crazy to have to shell out $100-$300 for simple SMTP functionality.

I read that setting the MaxIdleTime higher can help but I'm skeptical of that. I don't want to risk my app pool being disabled just because Microsoft doesn't want to follow the SMTP specification.

Edit: I looked at quiksoft.com components, however it does not support SMTP authentication and it costs $500. There's got to be a solution to this problem.

like image 326
JustAProgrammer Avatar asked May 30 '09 18:05

JustAProgrammer


1 Answers

In .NET 4.0, SmtpClient is now disposable. The SMTP QUIT command is issued upon disposal such as when used in a using block.

like image 190
Richard Collette Avatar answered Oct 08 '22 13:10

Richard Collette