简体   繁体   English

为什么 MailAddress 认为“john@gmail”。 是一个有效的电子邮件地址吗?

[英]Why does MailAddress think 'john@gmail.' is a valid email address?

Like a good C# user, I use the MailAddress object to validate email addresses.像一个优秀的 C# 用户一样,我使用MailAddress对象来验证电子邮件地址。

A client of mine entered john@gmail.我的一个客户输入了john@gmail. for his email, which was validated by MailAddress , and broke my software.他的电子邮件,经过MailAddress验证,破坏了我的软件。 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 .我认为在这种情况下,MS 对有效电子邮件地址的实现是不正确的,至少根据RFC822 I haven't actually tried your code, so I'm assuming it does as you say.我还没有真正尝试过你的代码,所以我假设它像你说的那样。

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 ).还有其他方法可以验证电子邮件地址,例如实际连接到 SMTP 服务器并要求它确认该地址是否有效(如此此处所述)。 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; eg 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.一个简单的电子邮件验证可以确认这一点,虽然我知道它可能并不适用于所有情况,但在那些情况下,你很不走运。

The MailAddress type has very limited support for validating email addresses and, as of .NET 4.0, does not support most of the related IETF standards. MailAddress 类型对验证电子邮件地址的支持非常有限,并且从 .NET 4.0 开始,不支持大多数相关的 IETF 标准。 If you need to validate the syntax of your email addresses, possibly without using regular expressions , I suggest you to take a look at EmailVerify.NET , a .NET component that supports all of the current standards about the subject (RFC 1123, RFC 2821, RFC 2822, RFC 3696, RFC 4291, RFC 5321 and RFC 5322).如果您需要验证电子邮件地址的语法,可能不使用正则表达式,我建议您查看EmailVerify.NET ,这是一个支持有关该主题的所有当前标准的 .NET 组件(RFC 1123、RFC 2821 、RFC 2822、RFC 3696、RFC 4291、RFC 5321 和 RFC 5322)。 Should you need to, the component even allows to perform additional tests on the addresses, including DNS, SMTP and mailbox checks.如果需要,该组件甚至允许对地址执行其他测试,包括 DNS、SMTP 和邮箱检查。

Disclaimer: I am the lead developer for this product.免责声明:我是该产品的首席开发人员。

MailboxValidator has a free API which you can use. MailboxValidator 有一个您可以使用的免费 API。 Just need to sign up for the free API plan at http://www.mailboxvalidator.com/plans#api then the integration part is pretty easy since they also have a C# class http://www.mailboxvalidator.com/dotnet for you to wrap the API calls.只需要在http://www.mailboxvalidator.com/plans#api上注册免费的 API 计划,那么集成部分就很容易了,因为他们还有一个 C# 类http://www.mailboxvalidator.com/dotnet你来包装 API 调用。

The C# class codes are in https://github.com/MailboxValidator/mailboxvalidator-csharp C# 类代码位于https://github.com/MailboxValidator/mailboxvalidator-csharp

To install MailboxValidator SingleValidation class via NuGet ( https://www.nuget.org/packages/MailboxValidator.SingleValidation/ ), run the following command in the Package Manager Console:要通过 NuGet ( https://www.nuget.org/packages/MailboxValidator.SingleValidation/ ) 安装 MailboxValidator SingleValidation 类, 在包管理器控制台中运行以下命令:

Install-Package MailboxValidator.SingleValidation

Then you can just use the class like below:然后你可以像下面这样使用这个类:

using System;
using System.Windows.Forms;
using MailboxValidator;

namespace TestMailboxValidatorCSharp
{
    public class TestMailboxValidatorCSharp
    {
        static void Main(string[] args)
        {
            var mbv = new SingleValidation("PASTE_YOUR_API_KEY_HERE");
            String results = "";
            try
            {
                MBVResult rec = mbv.ValidateEmail("example@example.com");

                if (rec.ErrorCode == "")
                {
                    results += "email_address: " + rec.EmailAddress + "\n";
                    results += "domain: " + rec.Domain + "\n";
                    results += "is_free: " + rec.IsFree + "\n";
                    results += "is_syntax: " + rec.IsSyntax + "\n";
                    results += "is_domain: " + rec.IsDomain + "\n";
                    results += "is_smtp: " + rec.IsSMTP + "\n";
                    results += "is_verified: " + rec.IsVerified + "\n";
                    results += "is_server_down: " + rec.IsServerDown + "\n";
                    results += "is_greylisted: " + rec.IsGreylisted + "\n";
                    results += "is_disposable: " + rec.IsDisposable + "\n";
                    results += "is_suppressed: " + rec.IsSuppressed + "\n";
                    results += "is_role: " + rec.IsRole + "\n";
                    results += "is_high_risk: " + rec.IsHighRisk + "\n";
                    results += "is_catchall: " + rec.IsCatchall + "\n";
                    results += "mailboxvalidator_score: " + rec.MailboxValidatorScore + "\n";
                    results += "time_taken: " + rec.TimeTaken + "\n";
                    results += "status: " + rec.Status + "\n";
                    results += "credits_available: " + rec.CreditsAvailable + "\n";
                }
                else
                {
                    results += "error_code: " + rec.ErrorCode + "\n";
                    results += "error_message: " + rec.ErrorMessage + "\n";
                }

                results += "version: " + rec.Version + "\n";
                MessageBox.Show(results);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }
    }
}

Somehow fixed version, mixing MailAddress and a simple Regex to validate the host:以某种方式固定版本,混合 MailAddress 和一个简单的 Regex 来验证主机:

Static regex, as advised by SLaks SLaks 建议的静态正则表达式

private static readonly Regex hostReg = new Regex(@"(\w+)\.(\w+)");

public bool IsMailAddress(string addParam)
        {
            try
            {
                MailAddress mail = new MailAddress(addParam);
                string address = mail.Address;

                //not handled by MailAdress, which is a shame
                return hostReg.IsMatch(mail.Host);
            }
            catch (FormatException)
            {
                //address is invalid
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

MailAddress tries to be compatible with RFC2822 which obsoletes RFC822. MailAddress 尝试与废弃 RFC822 的 RFC2822 兼容。 When you read the source code of MailAddress you see that the end-dot it's accepted just for compatibility with some e-mail clients.当您阅读 MailAddress 的源代码时,您会看到接受它的结尾点只是为了与某些电子邮件客户端兼容。 Validating e-mail address with regex is not the right thing to do (see RFC2822), the best way is to implement a parser, what MailAddress did.使用正则表达式验证电子邮件地址不是正确的做法(参见 RFC2822),最好的方法是实现解析器,MailAddress 所做的。

see DotAtomReader used by MailAddressParser 请参阅 MailAddressParser 使用的 DotAtomReader

Not a free solution but Cobisi's email validation library can tell whether the email valid or not within different level of accuracy (Syntax, IspSpecificSyntax, DeaDomain, Dns, DeaMailExchanger, Smtp, Mailbox, CatchAll)不是免费的解决方案,但Cobisi 的电子邮件验证库可以在不同的准确度(语法、IspSpecificSyntax、DeaDomain、Dns、DeaMailExchanger、Smtp、Mailbox、CatchAll)内判断电子邮件是否有效

var engine = new VerificationEngine();
var result = engine.Run("john@example.com",
                        VerificationLevel.Mailbox).Result;

if (result.LastStatus == VerificationStatus.Success)
{
    // TODO: Show a message box with the great news
}

Disclaimer: I am not related to the company or the project.免责声明:我与公司或项目无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM