如何使用 .NET Framework 验证电子邮件地址格式? [英] How do I validate email address formatting with the .NET Framework?

查看:30
本文介绍了如何使用 .NET Framework 验证电子邮件地址格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个函数来测试字符串的格式是否与电子邮件地址类似.

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 address = new MailAddress(input) 并且如果抛出,则无效.如果您的输入有任何可能的解释为符合 RFC 2822 的电子邮件地址规范,它将如此解析.上面的正则表达式,即使是 MSDN 文章之一,也是错误的,因为它们没有考虑显示名称、引用的本地部分、域的域文字值、本地部分的正确点原子规范,以及邮件地址可以在尖括号中、显示名称的多个带引号的字符串值、转义字符、显示名称中的 unicode、注释和最大有效邮件地址长度.我花了三个星期在 .NET 4.0 中为 System.Net.Mail 重新编写邮件地址解析器,相信我,这比提出一些正则表达式要困难得多,因为有很多边缘情况..NET 4.0 beta 2 中的 MailAddress 类将具有此改进的功能.

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.

这篇关于如何使用 .NET Framework 验证电子邮件地址格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆