HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Iterate over list and valid email address

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
addressemailiteratevalidandlistover

Problem

I have the following code:
(emailList type is List)

//Add All emails
foreach (var mail in emailList)
{
    var isEmail = Regex.IsMatch(mail.Trim(), @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

    if (isEmail)
    {
        email.BccRecipients.Add(mail.Trim());
        sbInfoLog.Append($"Email: {mail.Trim()}\n");
    }
    else
    {
        sbAlertLog.Append($"Not valid email address: {mail}\n");
    }
}


I'm looking for another way to:

  • To validate the email address



  • To Iterate over the list (Maybe with ForEach etc..)



Any suggestions?

Solution

This is a method I've used without any problems so far.

bool IsValidEmail(string email)
{
    try 
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch 
    {
        return false;
    }
}


To check the validity and handle each case you could do this.

var emailChecklist = emails.Select(x => 
    new { IsValid = IsValidEmail(x.Trim()), Address = x });

foreach(var email in emailChecklist)
{
    if (email.IsValid)
    {
        email.BccRecipients.Add(email.Address.Trim());
        sbInfoLog.Append($"Email: {email.Address.Trim()}\n");
    }
    else
    {
        sbAlertLog.Append($"Not valid email address: {email.Address}\n");
    }
}


I left the trim in the loop because I noticed that you didn't trim on the invalid email log. I assumed that you were trying to preserve the original value.

Code Snippets

bool IsValidEmail(string email)
{
    try 
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch 
    {
        return false;
    }
}
var emailChecklist = emails.Select(x => 
    new { IsValid = IsValidEmail(x.Trim()), Address = x });

foreach(var email in emailChecklist)
{
    if (email.IsValid)
    {
        email.BccRecipients.Add(email.Address.Trim());
        sbInfoLog.Append($"Email: {email.Address.Trim()}\n");
    }
    else
    {
        sbAlertLog.Append($"Not valid email address: {email.Address}\n");
    }
}

Context

StackExchange Code Review Q#156448, answer score: 14

Revisions (0)

No revisions yet.