许多人可能已经意识到,正确验证电子邮件地址可能有点噩梦。您可以整天搜索符合当前RFC标准的C#正则表达式,并且您会发现不同的正则表达式会给出不同的结果。System.Net.MailMessage允许一些无效的电子邮件地址格式
如果你看看http://en.wikipedia.org/wiki/Email_address#Local_part,你会发现在本地部分的开始或结尾处不允许有句点。连续两个时段也是不允许的。但是,以下NUnit测试证明System.Net.MailMessage允许您为一些无效的电子邮件地址格式实例化MailMessage对象。
[Test]
[TestCase(@"[email protected]")] //technically valid from the wiki article
[TestCase(@"[email protected][192.168.2.1]")] //technically valid from the wiki article
[TestCase(@"[email protected]")] //vanilla email address
[TestCase(@"[email protected]")] //also standard
[TestCase(@"[email protected]")] //long with lots of periods
[TestCase(@"[email protected]")] //disposable with the + symbol
[TestCase(@"[email protected]")] //period and dash in local part
[TestCase(@"[email protected]")] //lots of hyphens
[TestCase(@"!#$%&'*+-/=?^_`{|}[email protected]")] //all these symbols are allowed in local part
[TestCase(@"ër_%ل[email protected]كňil.com")] //characters outside the ascii range are permitted
[TestCase(@"""abcdefghixyz""@example.com")] //technically valid
//[TestCase(@"abc.""defghi""[email protected]")] //technically valid, but .NET throws exception
public void CanCreateMailMessageObjectTest(string emailAddress)
{
var mailMessage = new System.Net.Mail.MailMessage("[email protected]", emailAddress);
}
以上所有测试用例除最后一个都通过。
[Test]
[TestCase(@"[email protected]")] //leading period
[TestCase(@"[email protected]")] //period at end of local part <---FAIL
[TestCase(@"[email protected]")] //double period in local part <---FAIL
[TestCase(@"[email protected]!#$%^&*()=server.com")] //special characters in domain part
[TestCase(@"Abc.example.com")] //No @ separating local and domain part
[TestCase(@"[email protected]@[email protected]")] //more than one @ symbol
[TestCase(@"just""not""[email protected]")] //quoted strings must be dot separated
[TestCase(@"a""b(c)d,e:f;g<h>i[j\k][email protected]")] //special symbols "(),:;<>@[\] not inside quotes
[TestCase(@"[[email protected]")] //leading special symbol in local part
[TestCase(@"this is""not\[email protected]")] //spaces not in quotes
[TestCase(@"this\ still\""not\\[email protected]")] //backslashes not in quotes
[ExpectedException(typeof (System.FormatException))]
public void CannotCreateMailMessageObjectTest(string emailAddress)
{
var mailMessage = new System.Net.Mail.MailMessage("[email protected]", emailAddress);
}
为什么地球上做[email protected]
和[email protected]
未能抛出System.FormatException?这里谁错了,微软还是维基百科?是否有任何电子邮件地址可以追溯到期限或双倍期限?我的验证应该允许他们吗?我有适当的异常处理来允许我的电子邮件传送服务在发生异常时继续执行其日期,但是我想抛出无效或保证会引发异常的电子邮件地址。
感谢您发布您的3年半的解决方案,但那不是我真正想要的。我可以从FluentValidation和微软获得正则表达式,或者写我自己的,但问题是它们都是不同的。这篇文章并没有要求提供正则表达式,但问题为何MailMessage不会引发FormatException。 “ – jreancsu 2014-09-19 17:58:53