许多人可能已经知道,正确验证电子邮件地址可能会是一场噩梦。你可以整天搜索符合当前RFC标准的C#正则表达式,但你会发现不同的正则表达式会给出不同的结果。
如果你查看http://en.wikipedia.org/wiki/Email_address#Local_part,你会发现在本地部分开头或结尾的句点是不允许的。两个连续的句点也是不允许的。然而,以下NUnit测试证明了System.Net.MailMessage允许你为一些无效的电子邮件地址格式实例化一个MailMessage对象。
除了最后一个测试用例外,以上所有测试用例都通过了。
为什么
如果你查看http://en.wikipedia.org/wiki/Email_address#Local_part,你会发现在本地部分开头或结尾的句点是不允许的。两个连续的句点也是不允许的。然而,以下NUnit测试证明了System.Net.MailMessage允许你为一些无效的电子邮件地址格式实例化一个MailMessage对象。
[Test]
[TestCase(@"foobar@exampleserver")] //technically valid from the wiki article
[TestCase(@"jsmith@[192.168.2.1]")] //technically valid from the wiki article
[TestCase(@"niceandsimple@example.com")] //vanilla email address
[TestCase(@"very.common@example.com")] //also standard
[TestCase(@"a.little.lengthy.but.fine@dept.example.com")] //long with lots of periods
[TestCase(@"disposable.style.email.with+symbol@example.com")] //disposable with the + symbol
[TestCase(@"other.email-with-dash@example.com")] //period and dash in local part
[TestCase(@"user-test-hyphens@example-domain.com")] //lots of hyphens
[TestCase(@"!#$%&'*+-/=?^_`{|}~@example-domain.com")] //all these symbols are allowed in local part
[TestCase(@"ër_%لdev@gكňil.com")] //characters outside the ascii range are permitted
[TestCase(@"""abcdefghixyz""@example.com")] //technically valid
//[TestCase(@"abc.""defghi"".xyz@example.com")] //technically valid, but .NET throws exception
public void CanCreateMailMessageObjectTest(string emailAddress)
{
var mailMessage = new System.Net.Mail.MailMessage("noreply@example.com", emailAddress);
}
除了最后一个测试用例外,以上所有测试用例都通过了。
[Test]
[TestCase(@".test@example.com")] //leading period
[TestCase(@"test.@example.com")] //period at end of local part <---FAIL
[TestCase(@"test..example@example.com")] //double period in local part <---FAIL
[TestCase(@"foobar@example!#$%^&*()=server.com")] //special characters in domain part
[TestCase(@"Abc.example.com")] //No @ separating local and domain part
[TestCase(@"A@b@c@example.com")] //more than one @ symbol
[TestCase(@"just""not""right@example.com")] //quoted strings must be dot separated
[TestCase(@"a""b(c)d,e:f;g<h>i[j\k]l@example.com")] //special symbols "(),:;<>@[\] not inside quotes
[TestCase(@"[test@example.com")] //leading special symbol in local part
[TestCase(@"this is""not\allowed@example.com")] //spaces not in quotes
[TestCase(@"this\ still\""not\\allowed@example.com")] //backslashes not in quotes
[ExpectedException(typeof (System.FormatException))]
public void CannotCreateMailMessageObjectTest(string emailAddress)
{
var mailMessage = new System.Net.Mail.MailMessage("noreply@example.com", emailAddress);
}
为什么
test.@example.com
和 test..example@example.com
没有抛出 System.FormatException 异常?是 Microsoft 还是 Wikipedia 错了?是否有任何电子邮件地址被允许使用尾随句号或双句号?我应该允许它们通过验证吗?我已经设置了适当的异常处理,以便我的电子邮件投递服务在发生异常时继续运行,但我想排除无效或保证会引发异常的电子邮件地址。