验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?


当前回答

如果你真的,我是说真的想知道一个电子邮件地址是否有效……请邮件交换器来证明它,不需要正则表达式。如果需要,我可以提供代码。

一般步骤如下: 1. 电子邮件地址有域名部分吗?(@ > 0的索引) 2. 使用DNS查询询问域是否有邮件交换器 3.打开到邮件交换器的TCP连接 4. 使用SMTP协议,以电子邮件地址作为接收者打开到服务器的消息 5. 解析服务器的响应。 6. 如果你能走到这一步,就别发短信了,一切都好。

正如您可以想象的那样,这是非常昂贵的时间,并且依赖于smtp,但它确实有效。

其他回答

在c#的regex中有文化问题,而不是js。所以我们需要在US模式下使用regex进行邮件检查。如果你不使用ECMAScript模式,你的语言特殊字符是在A-Z与正则表达式中隐含的。

Regex.IsMatch(email, @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9_\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.ECMAScript)

一个简单的没有使用Regex(我不喜欢它的可读性差):

bool IsValidEmail(string email)
{
    string emailTrimed = email.Trim();

    if (!string.IsNullOrEmpty(emailTrimed))
    {
        bool hasWhitespace = emailTrimed.Contains(" ");

        int indexOfAtSign = emailTrimed.LastIndexOf('@');

        if (indexOfAtSign > 0 && !hasWhitespace)
        {
            string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);

            int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');

            if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
                return true;
        }
    }

    return false;
}

例子:

IsValidEmail(“@b.com”) // false IsValidEmail(“a@.com”) // false IsValidEmail(“a@bcom”) // false IsValidEmail(“a.b@com”) // false IsValidEmail(“a@b.”) // false IsValidEmail(“a b@c.com”) // false IsValidEmail(“a@b c.com”) // false IsValidEmail(“a@b.com”) // true IsValidEmail(“a@b.c.com”) // true IsValidEmail(“a+b@c.com”) // true IsValidEmail(“a@123.45.67.89”) // true

它意味着简单,因此它不处理罕见的情况,如电子邮件的括号域包含空格(通常是允许的),电子邮件的IPv6地址等。

基于@Cogwheel的回答,我想分享一个修改后的解决方案,适用于SSIS和“脚本组件”:

Place the "Script Component" into your Data Flow connect and then open it. In the section "Input Columns" set the field that contains the E-Mail Adresses to "ReadWrite" (in the example 'fieldName'). Switch back to the section "Script" and click on "Edit Script". Then you need to wait after the code opens. Place this code in the right method: public override void Input0_ProcessInputRow(Input0Buffer Row) { string email = Row.fieldName; try { System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email); Row.fieldName= addr.Address.ToString(); } catch { Row.fieldName = "WRONGADDRESS"; } }

然后,您可以使用条件分割过滤掉所有无效记录或任何您想做的事情。

这是一个老问题,但我在SO上找到的所有答案,包括最近的答案,都与这个问题类似。然而,在。net 4.5 / MVC 4中,你可以通过从System.ComponentModel中添加[EmailAddress]注释来向表单添加电子邮件地址验证。DataAnnotations,所以我想知道为什么我不能只使用。net的内置功能。

这似乎是可行的,而且在我看来是相当优雅的:

using System.ComponentModel.DataAnnotations;

class ValidateSomeEmails
{
    static void Main(string[] args)
    {
        var email = new EmailAddressAttribute();
        email.IsValid("someone@somewhere.com");         //true
        email.IsValid("someone@somewhere.co.uk");       //true
        email.IsValid("someone+tag@somewhere.net");     //true
        email.IsValid("futureTLD@somewhere.fooo");      //true
        
        email.IsValid("fdsa");                          //false
        email.IsValid("fdsa@");                         //false
        email.IsValid("fdsa@fdsa");                     //false
        email.IsValid("fdsa@fdsa.");                    //false

        //one-liner
        if (new EmailAddressAttribute().IsValid("someone@somewhere.com")) 
            return true;
    }
}

Personally, I would say that you should just make sure there is an @ symbol in there, with possibly a . character. There's many regexes you could use of varying correctness, but I think most of these leave out valid email addresses, or let invalid ones through. If people want to put in a fake email address, they will put in a fake one. If you need to verify that the email address is legit, and that the person is in control of that email address, then you will need to send them an email with a special coded link so they can verify that it indeed is a real address.