0

I'm trying to remove or exclude a couple specific e-mail addresses from the CC e-mail address list. How should I do this? Here is the function:

private void SendEmail(string emailTo, string subject, string body)
{
    using (SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SmtpServerAddress"]))
    {
        MailMessage email = new MailMessage();
        email.From = new MailAddress(GetUserEmail());
        string emailCc = ConfigurationManager.AppSettings["EmailCc"];
        foreach (var item in emailTo.Split(';'))
        {
            email.To.Add(new MailAddress(item.Trim()));
        }
        foreach (var item in emailCc.Split(';'))
        {
            email.CC.Add(new MailAddress(item.Trim()));
        }
        email.Subject = subject;
        email.IsBodyHtml = true;
        email.Body = body;

        return;
   }
}
Magnetron
  • 7,495
  • 1
  • 25
  • 41

2 Answers2

0

You put the emails you don't want into an array:

var badEmails = new [] { "a@a.aa", "b@b.bb" }

Then you use LINQ to remove them from the split:

var ccList = emailCc.Split(';').Where(cc => !badEmails.Any(b => cc.IndexOf(b, System.StringComparison.InvariantCultureIgnoreCase) > -1));

Then you add those in ccList to your email

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

You can try with this if you know email:

foreach (var item in emailCc.Split(';'))
{
    if (!new string[] { "bad@gmail.com", "uncle@sam.com", "stack@overflow.com"}.Contains(email))
    {
        email.CC.Add(new MailAddress(item.Trim()));
    }
            
}

instead of if statement you can use regular expression if you want to exclude some email with specific pattern.

TJacken
  • 354
  • 3
  • 12