Remove To and BCC Addresses using System.Net.Mail

4.6k Views Asked by At

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?

3

There are 3 best solutions below

3
On BEST 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
    ...
}
0
On

I had the same problem in one code of mine...

Try this:

MailMessage mailMessage = new MailMessage();

while (dr.Read())
{
//Your code from HERE
    mailMessage.To.Add(new MailAddress(dr["EmailAddress"].ToString()));

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

    // Send email
    ...
    //Then email delete from .To
    int iMessageInArray = mailMessage.To.Count(); //Finds the amount of emails in the array

    if(iMessageInArray > 0)
    {
       for(int i = 0; i < iMessageInArray; i++)
       {
           mailMessage.To.Remove(mailMessage.To[0]); //When one line is removed, the next email comes in index 0 of the array.
        }
    }
}
1
On
    var adresse = dr["SecondaryEmail"].ToString();
    int iMessageInArray = mailMessage.To.Count();
    if(iMessageInArray > 0)
    {
        foreach (var mailadress in mailMessage.To)
        {
            if (mailadress.Address == adresse)
            {
                mailMessage.To.Remove(mailadress);
            }
        }
    }