Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods for MailMessage Bcc AddRange

When adding multiple recipients to a MailMessage.BCC there is no option for AddRange(). Only MailMessage.Bcc.Add();

Can this functionality be changed by an extension method? I'm a little lost at this point, any pointers would be very much appreciated.

like image 868
Dave Avatar asked Apr 14 '26 14:04

Dave


2 Answers

Supposing you are talking about the System.Net.Mail.MailMessage class, what you need is already provided by the MailAddressCollection.Add method (Bcc is of the MailAddressCollection type).

Just call Add method with multiple e-mail addresses separated by a comma character (",").

Check this:

http://msdn.microsoft.com/en-us/library/ms144695(v=vs.100).aspx

like image 87
Catalin M. Avatar answered Apr 16 '26 03:04

Catalin M.


MailMessage.Bcc is of type MailAddressCollection. This MailAddressCollection implements ICollection<MailAddress>. So what you can do, is write a generic AddRange extension method which applies to any ICollection<T>.

This will look like the following:

public static class CollectionExtensions
{
    public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> items)
    {
        foreach(var item in items)
        {
            target.Add(item);
        }   
    }
}

You can then use this like so:

var address1 = new MailAddress("[email protected]");
var address2 = new MailAddress("[email protected]");
message.Bcc.AddRange(new[] { address1, address2 });
like image 22
Lukazoid Avatar answered Apr 16 '26 02:04

Lukazoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!