C# .NET 验证Email是否正确

验证字符串是否为有效的电子邮件格式

示例

该示例定义 IsValidEmail 方法,如果字符串包含有效的电子邮件地址,则该方法返回 true ,否则返回 false ,但不采取其他任何操作。

请注意, IsValidEmail 方法不执行身份验证来验证电子邮件地址。 它只确定其格式对于电子邮件地址是否有效。 此外, IsValidEmail 方法不对顶级域名是否是 IANA 根区域数据中列出的有效域名进行验证,这需执行查找操作。 相反,正则表达式仅验证由二到二十四个 ASCII 字符组成的顶级域名,该域名以字母数字开头并以字符结尾,且其余的字符是字母数字或连字符 (-)。

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtil
{
    public static bool IsValidEmail(string email)
    {
        if (string.IsNullOrWhiteSpace(email))
            return false;

        try
        {
            // Normalize the domain
            email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                  RegexOptions.None, TimeSpan.FromMilliseconds(200));
        }
        catch (RegexMatchTimeoutException e)
        {
            return false;
        }
        catch (ArgumentException e)
        {
            return false;
        }

        try
        {
            return Regex.IsMatch(email,
                @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        }
        catch (RegexMatchTimeoutException)
        {
            return false;
        }
    }
    static string DomainMapper(Match match)
    {
        // Use IdnMapping class to convert Unicode domain names.
        var idn = new IdnMapping();

        // Pull out and process domain name (throws ArgumentException on invalid)
        var domainName = idn.GetAscii(match.Groups[2].Value);

        return match.Groups[1].Value + domainName;
    }
}