Sending e-mails from your ASP.NET app and maintaining a list of recipients

Making your application send e-mails, is something you do almost in every application. It’s easy – all you need is an SMTP server to relay your mail through. Sending e-mail messages to several recipients at once can also be done, by adding multiple recipients to either of the MailMessage.To, MailMessage.Cc or MailMessage.Bcc properties in C#. But if you send a newsletter every month, week or day, it is very important to maintain your list of recipients, so that whenever people get a new e-mail address (and they do!) and the old one stop working – you avoid those undelivered mails everytime you send your newsletter.

I’ve made this simple class called BulkSender, that takes three parameters in the constructor:
mailMessage (System.Net.Mail.MailMessage), recipients (List), mailSender (System.Net.Mail.SmtpClient).

It has one method: SendEmailMessage, and what it does is, that it adds all recipients to the Bcc collection on the MailMessage, and sends the mail in a try-catch block. Whenever the SmtpFailedRecipientsException or SmtpFailedRecipientException is handled, it adds the e-mail address to a local List and returns the e-mail addresses with delivery failures as a List.

Code snippet:
[image

When you get the List of failed recipients, you can add your own logic to take care of maintaining your list of recipients. Maybe an e-mail address has to fail 3 times, before it is deleted, or maybe you want to delete it the first time it fails.

Another good thing to have in mind when sending e-mails to multiple recipients at once, is to add the mail addresses to the Bcc collection, and NOT the To or Cc collection. This way the e-mail addresses is hidden, you only get to see ‘undisclosed-recipients’ in you mail client:
[image

Note that the BulkSender class automatically clears the To, Cc and Bcc collections before adding the recipients to the Bcc collection. This way you know for sure, that you do not have any e-mail addresses publicly available when you send the e-mail.

You can download the code below. Feel free to tweak the class – and let me know if you have some interesting things regarding this topic.

Technorati Tags: [ASP.NET](http://technorati.com/tags/ASP.NET), [C#](http://technorati.com/tags/C#)
[BulkSender.zip (818.00 bytes)](/file.axd?file=BulkSender.zip)

kick it on DotNetKicks.com