如何验证的电子邮件地址与.NET Framework格式?电子邮件地址、格式、NET、Framework

2023-09-02 01:40:27 作者:哭都没声音

我想一个函数来测试一个字符串格式化像一个电子邮件地址。

I want a function to test that a string is formatted like an email address.

随之而来内置的.NET框架来做到这一点?

What comes built-in with the .NET framework to do this?

本作品:

Function IsValidEmailFormat(ByVal s As String) As Boolean
    Try
        Dim a As New System.Net.Mail.MailAddress(s)
    Catch
        Return False
    End Try
    Return True
End Function

不过,有没有更好的方法?

But, is there a more elegant way?

推荐答案

不要打扰自己的验证。 .NET 4.0已经显著提高通过MailAddress类。只需使用 MailAddress地址=新MailAddress(输入),如果它抛出,这是无效的。如果有任何可能的相互$ P $您输入的作为一个RFC 2822兼容的电子邮件地址规格ptation,它将解析它是这样。因为他们没有考虑到的显示名称,援引当地部分,对于域的域文字值,正确点原子规格为当地的一部分,可能是上面的正则表达式,甚至MSDN文章之一,是错误的一邮件地址可以是在尖括号中,为显示名称的多个引用字符串值,转义字符,单code中的显示名称,注释和最大有效邮箱地址长度。我花了重新写在.NET 4.0中的System.Net.Mail邮件地址解析器三个星期,相信我,这是路难比刚刚出现了一些常规的前pression,因为有大量的边缘案件。该 MailAddress 类.NET 4.0 Beta 2中都会有这样的改进的功能。

Don't bother with your own validation. .NET 4.0 has significantly improved validation via the MailAddress class. Just use MailAddress address = new MailAddress(input) and if it throws, it's not valid. If there is any possible interpretation of your input as an RFC 2822 compliant email address spec, it will parse it as such. The regexes above, even the MSDN article one, are wrong because they fail to take into account a display name, a quoted local part, a domain literal value for the domain, correct dot-atom specifications for the local part, the possibility that a mail address could be in angle brackets, multiple quoted-string values for the display name, escaped characters, unicode in the display name, comments, and maximum valid mail address length. I spent three weeks re-writing the mail address parser in .NET 4.0 for System.Net.Mail and trust me, it was way harder than just coming up with some regular expression since there are lots of edge-cases. The MailAddress class in .NET 4.0 beta 2 will have this improved functionality.

还有一件事,你可以验证的唯一一件事就是邮件地址的格式。你永远不能验证的电子邮件地址实际上是有效的,而不发送电子邮件到该地址,如果服务器接受它交付看到接收电子邮件。这是不可能的,同时也有SMTP命令可以给你的邮件服务器来尝试验证它,很多时候,这些将被禁用或将返回不正确的结果,因为这是垃圾邮件发送者发现电子邮件地址的常用方法。

One more thing, the only thing you can validate is the format of the mail address. You can't ever validate that an email address is actually valid for receiving email without sending an email to that address and seeing if the server accepts it for delivery. It is impossible and while there are SMTP commands you can give to the mail server to attempt to validate it, many times these will be disabled or will return incorrect results since this is a common way for spammers to find email addresses.