【问题标题】:Best way to validate email address format in C#在 C# 中验证电子邮件地址格式的最佳方法
【发布时间】:2020-02-14 21:13:44
【问题描述】:

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

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 对每个用户来说似乎非常昂贵,只是为了验证电子邮件地址格式。我想知道使用正则表达式,但不确定这是否有助于提高性能。

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

【问题讨论】:

  • 您可能会从这个问题中找到一些有用的答案:stackoverflow.com/questions/1365407/…
  • 是的,Daniel,我查看了帖子,但对于性能问题(如果有的话)并不清楚。
  • 您确定这里存在明显的性能问题吗?如果是这样,您可以尝试提前验证电子邮件地址,但这是非常棘手的事情。请参阅this page 了解可能对您有用的正则表达式。此外,重复的问题还有其他可能具有更好性能的答案。如果您认为这不是重复的,请说明您正在衡量哪些性能指标以及您的性能目标是什么。
  • 我不确定使用正则表达式验证电子邮件是否会对仅 2000 个值的性能产生显着影响。但是,使用异常处理进行验证是非常不受欢迎的,因此无论性能如何,都可以进行适当的验证。
  • @RacilHilan 当然有额外的验证是好的,但在某些时候你需要在调用周围的try/catch 来创建一个新的MailAddress,不是吗?跨度>

标签: c# performance validation try-catch mailaddress


【解决方案1】:

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

由于源代码可用,请查看ParseAddress 方法here,您将了解自己验证电子邮件地址所必须编写的代码。很遗憾,我们没有可以用来避免抛出异常的公共 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 2013-12-05
    • 2012-04-08
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多