Sun*_*rya 2 c# email validation
我在我的 c# windows 应用程序中使用 smtp 服务发送电子邮件。我必须以最佳方式执行以降低电子邮件退回率。我必须检查提供的电子邮件地址是否有效。我正在使用代码。
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;
}
Run Code Online (Sandbox Code Playgroud)
通过检查真实域,我可以识别托管 IP,但电子邮件地址是否在主机上创建。
使用正则表达式(正则表达式)我只能使用格式。
所以我的问题是如何在 c# 中只找到任何域的有效地址。
您可以System.ComponentModel.DataAnnotations通过以下方式导入和使用它:
private bool validMail(string address)
{
EmailAddressAttribute e = new EmailAddressAttribute();
if (e.IsValid(address))
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
如果您想验证特定域,正如您在评论中所说,那就更简单了:
Regex rx = new Regex(
@"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@yourdomain.com$");
Run Code Online (Sandbox Code Playgroud)
将 yourdomain.com 替换为您的域名。
| 归档时间: |
|
| 查看次数: |
22431 次 |
| 最近记录: |