简体   繁体   English

如何检查电子邮件是否为有效格式

[英]How to check if email is valid format or not

The below email is not valid format 以下电子邮件格式无效

fulya_42_@hotmail.coö

But all validations i found and tried so far with c# said it is correct email which is not 但是到目前为止,我发现并尝试使用C#进行的所有验证都表明这是正确的电子邮件,但不是

How can i validate email is valid or not with c# 4.5.2? 如何使用C#4.5.2验证电子邮件是否有效? thank you 谢谢

Ok updated question 确定更新的问题

The reason i am asking is one of the biggest email service mandrill api throws internal server error when you try to email this address 我要问的原因是最大的电子邮件服务mandrill api之一,当您尝试通过电子邮件发送此地址时会引发内部服务器错误

So they must be using some kind of validation before even trying to send out email. 因此,他们甚至在尝试发送电子邮件之前都必须使用某种验证。 My aim is finding what are they using to eliminate such emails before try thank you 我的目的是在尝试谢谢之前先找到他们用什么来消除此类电子邮件

By using Regex 通过使用正则表达式

string emailID = "fulya_42_@hotmail.coö";

        bool isEmail = Regex.IsMatch(emailID, @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");

        if (isEmail)
        {
            Response.Write("Valid");
        }

Check the below class from https://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx https://msdn.microsoft.com/zh-cn/library/01escwtf(v=vs.110).aspx检查以下类

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtilities
{
   bool invalid = false;

   public bool IsValidEmail(string strIn)
   {
       invalid = false;
       if (String.IsNullOrEmpty(strIn))
          return false;

       // Use IdnMapping class to convert Unicode domain names. 
       try {
          strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper,
                                RegexOptions.None, TimeSpan.FromMilliseconds(200));
       }
       catch (RegexMatchTimeoutException) {
         return false;
       }

        if (invalid)
           return false;

       // Return true if strIn is in valid e-mail format. 
       try {
          return Regex.IsMatch(strIn,
                @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
       }
       catch (RegexMatchTimeoutException) {
          return false;
       }
   }

   private string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.
      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;
      try {
         domainName = idn.GetAscii(domainName);
      }
      catch (ArgumentException) {
         invalid = true;
      }
      return match.Groups[1].Value + domainName;
   }
}

Or take a look at @Cogwheel answer here C# code to validate email address 或在此处查看@Cogwheel答​​案C#代码以验证电子邮件地址

Regular expression for e-mail address can be matched using below : 可以使用以下方式匹配电子邮件地址的正则表达式:

 return Regex.IsMatch(strIn, 
              @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + 
              @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", 
              RegexOptions.IgnoreCase);

Reference MSDN 参考MSDN

But in your case : 但是在您的情况下:

fulya_42_@hotmail.coö

If you are checking the validity of email address from the " .coo " which is not valid as per your observation, it will not show any error as the regex doesnt validate that,hence you have to manually add some domains which you accept like : gmail.com , yahoo.com etc. 如果您正在从“ .coo ”中检查电子邮件地址的有效性(根据您的观察是无效的),则它不会显示任何错误,因为regex不会对此进行验证,因此您必须手动添加一些您接受的域,例如: gmail.com,yahoo.com等。

rightly said in the comments for the question by SonerGonul 在SonerGonul对问题的评论中正确地说

Thanks 谢谢

First off, the email address you provided is in a valid format . 首先,您提供的电子邮件地址采用有效格式 -- You can take it a step further and verify if the domain is valid or not as well, if you like; -您可以更进一步,并根据需要验证域是否有效; but either way, you should be validating ownership, in which case, you will know that the email address and domain are valid. 但是无论哪种方式,您都应该验证所有权,在这种情况下,您将知道电子邮件地址和域是有效的。

Secondly, you should really not be using Regex to validate an email address; 其次,您实际上应该使用Regex来验证电子邮件地址。 email address validation is built-in to the .NET framework, and you shouldn't be recreating the wheel for something like this. 电子邮件地址验证内置于.NET框架中,因此您不应该为这种情况重新创建轮子。

A simple validation function that performs both checks, looks like this: 一个执行两个检查的简单验证函数如下所示:

public static bool IsValidEmailAddress(string emailAddress, bool verifyDomain = true)
{
    var result = false;
    if (!string.IsNullOrWhiteSpace(emailAddress))
    {
        try
        {
            // Check Format (Offline).
            var addy = new MailAddress(emailAddress);

            if (verifyDomain)
            {
                // Check that a valid MX record exists (Online).
                result = new DnsStubResolver().Resolve<MxRecord>(addy.Host, RecordType.Mx).Any();
            }
            else
            {
                result = true;
            }
        }
        catch (SocketException)
        {
            result = false;
        }
        catch (FormatException)
        {
            result = false;
        }
    }

    return result;
}

To run the code, you will need to install the NuGet package ARSoft.Tools.Net , which is required for MX record lookup*, and you will need to add the appropriate using declarations for the various classes used (should be pretty automatic in VisualStudio these days). 要运行代码,您需要安装NuGet包ARSoft.Tools.Net ,这是MX记录查找*所必需的,并且需要为所使用的各种类添加适当的using声明(在VisualStudio中应该是非常自动的)这些日子)​​。

(*: Simply checking for a valid host name via System.Net.Dns.GetHost* is not enough, as that can give you some false negatives for some domains which only have MX entries, such as admin@fubar.onmicrosoft.com , etc.) (*:仅通过System.Net.Dns.GetHost*检查有效的主机名是不够的,因为对于某些只有MX条目的域,例如admin@fubar.onmicrosoft.com ,这可能会给您带来一些负面的负面admin@fubar.onmicrosoft.com ,等等。)

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

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