Design for a mass e-mailer in an ASP.NET page — is just a foreach loop and SmtpClient sufficient?

StackOverflow https://stackoverflow.com/questions/12925936

سؤال

We are interested in implementing something into our ASP.NET web application that will send out an e-mail to addresses pulled from SQL Server 2008.

This doesn't seem like it would be that difficult. Pseudo-code:

EmailAddressList addresses = EmailAddressManager.GetList();

foreach (EmailAddress x in addresses)
{
    MailMessage msg = new MailMessage("fromaddress@test.com", x.ToAddress);
    //prepare msg, body, subject, etc.

    SmtpClient smtp = new SmtpClient();
    smtp.Send(msg);

    //add artificial delay for throttling?  this seems to be a common tactic
}

This question has an upvoted comment that links to something that was supposedly helpful, but now just leads to a Page Not Found error.

And in this question, the OP says specifically that the above pseudo-code method isn't "the good way." But what is wrong with it? Is there a common or better practice for this? Are there hidden pitfalls I'm not taking into account?

And just a little bit more detail about our situation: this will only be used maybe twice per month, and the number of emails to be sent at once will not be above roughly 30 or 40. The end goal is, we go to this page that has this tool, we can preview what's going to get sent out and to who, and then we just press a button and it executes the above pseudo-code.

هل كانت مفيدة؟

المحلول

I don't think there's anything wrong with a loop like you're doing, but there are a few things you probably need to handle. The most important would probably be error handling. If one of the emails fails, you'll just break out having sent emails to a subset of people, and it'll be tough to deal with should you need to send to the rest. Even if you have some simple try-catch, you'll still have a problem retrying those emails. You'll want to have some way of storing all the emails you planned on sending to and the results of each send.

Next will be performance-related. Sending emails one at a time using .Send() is going to be slow if it's a lot of emails. An easy way around it is to use the Task library or the Async version to multithread the sends. Of course this makes the state management a little more complicated, but it will improve email sending speed significantly. If you have a limit to the number of emails you can send per minute/hour, then that may or may not be at odds with this optimization.

If you have different content for each recipient you'll probably want to use some templating library like NVelocity or the MS Razor Engine.

Or you could just outsource this boring stuff to somewhere like SendGrid.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top