0

嗨,我正在开发批量电子邮件发送功能。下面是我验证电子邮件并将其发送给每个收件人的循环:

foreach (var userID in recipientUserIds)
{
    var userInfo = //getting from database using userID.

    try
    {
        to = new MailAddress(userInfo.Email1, userInfo.FirstName + " " + userInfo.LastName);
    }
    catch (System.FormatException fe)
    {
        continue;
    }

    using (MailMessage message = new MailMessage(from, to))
    {
        //populate message and send email.
    }
}

由于 recipientUserIds 总是超过 2000,因此在这种情况下使用 try-catch 对每个用户来说似乎非常昂贵,只是为了验证电子邮件地址格式。我想知道使用正则表达式,但不确定这是否有助于提高性能。

所以我的问题是是否有更好或性能优化的方法来进行相同的验证。

4

1 回答 1

1

验证电子邮件地址是一项复杂的任务,编写代码来预先完成所有验证将非常棘手。如果您查看类文档Remarks的部分,您会看到有很多字符串被认为是有效的电子邮件地址(包括注释、括号内的域名和嵌入的引号)。MailAddress

由于源代码可用,请查看此处ParseAddress的方法,您将了解自己验证电子邮件地址所必须编写的代码。遗憾的是,没有我们可以使用的公共方法来避免抛出异常。TryParse

所以最好先做一些简单的验证——确保它包含对电子邮件地址的最低要求(字面意思是user@domain,其中domain不必包含'.'字符),然后让异常处理处理休息:

foreach (var userID in recipientUserIds)
{
    var userInfo = GetUserInfo(userID);

    // Basic validation on length
    var email = userInfo?.Email1?.Trim();
    if (string.IsNullOrEmpty(email) || email.Length < 3) continue;

    // Basic validation on '@' character position
    var atIndex = email.IndexOf('@');
    if (atIndex < 1 || atIndex == email.Length - 1) continue;

    // Let try/catch handle the rest, because email addresses are complicated
    MailAddress to;
    try
    {
        to = new MailAddress(email, $"{userInfo.FirstName} {userInfo.LastName}");
    }
    catch (FormatException)
    {
        continue;
    }

    using (MailMessage message = new MailMessage(from, to))
    {
        // populate message and send email here
    }
}
于 2019-10-17T23:04:27.357 回答