IrishChieftain IrishChieftain - 3 months ago 29
ASP.NET (C#) Question

Remove To and BCC Addresses using System.Net.Mail

I'm upgrading a mass mailer application to use the new System.Net.Mail namespace. I'm also setting up AlternateViews for text and HTML versions.

Currently I'm using a DataReader to grab email addresses from the DB and send out the mails. In the old code, I would clear out the To and BCC properties at the end of the loop.

MailMessage mailMessage = new MailMessage();

while (dr.Read())
{
....
mailMessage.To.Add(new MailAddress(dr["EmailAddress"].ToString()));

if ((bool)dr["SecondaryNotify"])
mailMessage.Bcc.Add(new MailAddress(dr["SecondaryEmail"].ToString()));

// Send email
...
}


Apparently there is a Remove method that can be called on the To property of the MailMessage class mailMessage.To.Remove(MailAddress item) - I have determined this from intellisense. I have checked MSDN and cannot find an example of this usage.

Can anyone assist with syntax to remove To and BCC addresses for each iteration of the loop - after each email has been sent?

Answer

Go with a simpler solution. Just instantiate the MailMessage in your while loop. Then you have no need to remove anything.

while (dr.Read())
{
    var mailMessage = new MailMessage();
    ....
    mailMessage.To.Add(new MailAddress(dr["EmailAddress"].ToString()));

    if ((bool)dr["SecondaryNotify"])
        mailMessage.Bcc.Add(new MailAddress(dr["SecondaryEmail"].ToString()));

    // Send email
    ...
}
Comments