简体   繁体   English

在C#中检查有效的电子邮件地址

[英]Check Valid email address in c#

I'm sending email using smtp services in my c# windows application. 我正在c#Windows应用程序中使用smtp服务发送电子邮件。 I have to perform in a best way to reduce the email bounce rate. 我必须以最佳方式执行以降低电子邮件跳出率。 I have to check the provided email address is valid or not. 我必须检查提供的电子邮件地址是否有效。 I'm using the code. 我正在使用代码。

    private void btnCheckValid_Click(object sender, EventArgs e)
        {
            if (isRealDomain(textBox1.Text.Trim()) == true)
                MessageBox.Show("Valid Email Address!");
        }
        private bool isRealDomain(string inputEmail)
        {
            bool isReal = false;
            try
            {
                string[] host = (inputEmail.Split('@'));
                string hostname = host[1];

                IPHostEntry IPhst = Dns.GetHostEntry(hostname);
                IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
                Socket s = new Socket(endPt.AddressFamily,
                        SocketType.Stream, ProtocolType.Tcp);
                s.Connect(endPt);
                s.Close();
                isReal = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isReal = false;
            }

            return isReal;
        }

By checking the real domain I can identified the Hosted IP but the email address is created on the host or not. 通过检查真实域,我可以识别托管IP,但是是否在主机上创建了电子邮件地址。

with regex (regular expression ) I can valid only format. 使用正则表达式(正则表达式),我只能验证格式。

So my question is how to find only valid address of any domain in c#. 所以我的问题是如何在c#中仅查找任何域的有效地址。

You can import System.ComponentModel.DataAnnotations and use it in this way: 您可以导入System.ComponentModel.DataAnnotations并以这种方式使用它:

private bool validMail(string address)
{
    EmailAddressAttribute e = new EmailAddressAttribute();
    if (e.IsValid(address))
        return true;
    else
        return false;
}

You can use regular expressions like: 您可以使用如下正则表达式:

    public static bool IsValidEmailAddress(string emailaddress)
    {
        try
        {
            Regex rx = new Regex(
        @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
            return rx.IsMatch(emailaddress);
        }
        catch (FormatException)
        {
            return false;
      }
}

UPDATE: 更新:

If you want to validate for a specific domain as you said in comments its even simpler: 如果您要按照评论中的说明验证特定域,则更为简单:

Regex rx = new Regex(
@"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@yourdomain.com$");

Replace yourdomain.com with your domain name. 用您的域名替换yourdomain.com。

Using the .Net mail namespace you can verify email address like this: 使用.Net邮件命名空间,您可以像这样验证电子邮件地址:

using System.Net.Mail;

private bool EmailVerify(string email)

    {
        try
        {
            var mail = new MailAddress(email);

            return mail.Host.Contains(".");
        }
        catch
        {
            return false;
        }
    }

If you are using 如果您正在使用

System.Net.Mail.SmtpClient

The most accurate way I've found is to attempt to create a 我发现的最准确的方法是尝试创建一个

System.Net.Mail.MailAddress

object. 宾语。 If you cannot create the object with the address in your string it will throw one of the following: 如果无法使用字符串中的地址创建对象,则将引发以下其中一项:

ArgumentNullException // The address is null
ArgumentException // The address is string.Empty
FormatException // The address is not in a recognized format

https://msdn.microsoft.com/en-us/library/591bk9e8(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/591bk9e8(v=vs.110).aspx

I've found that 我发现

Dns.GetHostEntry

is iffy at best. 充其量是无聊的。 It does not seem to recognize multilayered domains as valid (domain.subdomain1.subdomain2.com), so checking the domain using that method is NOT definitive. 它似乎无法识别多层域为有效域(domain.subdomain1.subdomain2.com),因此使用该方法检查域不是确定的。

Using a RegEx is ok, but they often fail to recognize quoted addresses and other valid patterns (which are fine according to the RFC) as valid. 使用RegEx是可以的,但是它们通常无法将引用的地址和其他有效模式(根据RFC可以使用)识别为有效。

Since, to use the SmtpClient class you have to have a valid MailAddress object anyway, it just makes sense. 由于要使用SmtpClient类,无论如何都必须具有有效的MailAddress对象,这很有意义。

Here is an another way to check valid email address 这是检查有效电子邮件地址的另一种方法

 public bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
 public static bool IsValidEmail(string emailaddress)
    {
           return new EmailAddressAttribute().IsValid(emailaddress);
    }
// using System.ComponentModel.DataAnnotations;

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

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