本文介绍了为什么MailAddress认为“ john @ gmail”。是有效的电子邮件地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像一个好的C#用户一样,我使用对象来验证电子邮件地址。

Like a good C# user, I use the MailAddress object to validate email addresses.

我的一个客户输入了 john @ gmail。的电子邮件(已通过 MailAddress 验证),并破坏了我的软件。我希望下面的代码抛出异常,但不会。

A client of mine entered john@gmail. for his email, which was validated by MailAddress, and broke my software. I'd expect the code below to throw an exception, but it doesn't.

static void Main(string[] args)
{
    string addressmail = string.Empty;

    try
    {
        MailAddress mail = new MailAddress(@"john@gmail.");
        addressmail = mail.Address;
    }
    catch (FormatException)
    {
        // address is invalid
    }

    // address is valid
    Console.WriteLine(addressmail);
}

您知道如何捕获这种虚假的邮件地址吗?

Do you know how to catch this kind of bogus mail address?

推荐答案

我认为在这种情况下,至少对于。我实际上并没有尝试过您的代码,所以我假设它按照您所说的进行。

I think in this case, MS's implementation of a valid email address is incorrect, at least as per RFC822. I haven't actually tried your code, so I'm assuming it does as you say.

还有其他验证电子邮件地址的方法,例如实际连接到SMTP服务器并要求其确认地址有效(如所述, )。否则,您总会遇到麻烦。就个人而言,我不认为花太多时间根据某种规范来验证电子邮件地址是值得的(除了我们可以使用的快速检查;例如您的代码)-真正的测试是是否在该地址上收到了电子邮件如果您发送它。一个简单的电子邮件验证可以确认这一点,尽管我知道可能并不适合所有情况,但是在那种情况下,您很不走运。

There are other ways to validate email addresses, such as actually connecting to the SMTP server and asking it to confirm that the address is valid (as explained here and here). Short of doing that, you will always have a bit of trouble. Personally, I don't think that it's worthwhile to spend too much time validating email address according to some specification (beyond the quick checks we have at our disposal; e.g. your code) - the real test is whether an email is received on that address if you send it. A simple email verification can confirm this, although I know it might not be appropriate in all cases, but in those, you are out of luck.

这篇关于为什么MailAddress认为“ john @ gmail”。是有效的电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 10:16