How to exclude or remove a specific e-mail address from a sendEmail function in c#

972 views Asked by At

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;
   }
}
2

There are 2 answers

0
TJacken On BEST ANSWER

You can try with this if you know email:

foreach (var item in emailCc.Split(';'))
{
    if (!new string[] { "[email protected]", "[email protected]", "[email protected]"}.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.

0
Caius Jard On

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

var badEmails = new [] { "[email protected]", "[email protected]" }

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