验证电子邮件地址 [英] Validating an email address

查看:170
本文介绍了验证电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码使用c#发送电子邮件。

I am trying to send an email using c# using the following code.

MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress, friendlyName);
mail.To.Add(toAddress);
mail.CC.Add(ccAddress);

//set the content
mail.Subject = emailSubject;
mail.Body = emailHeader + "\n" + emailBody;

//send the message
SmtpClient smtp = new SmtpClient(ServerAddress);
smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
mail.IsBodyHtml = true;
smtp.Send(mail);

现在 toAddress字符串表明我的函数接收的地址可能包含一个地址,或者可能有多个地址,以逗号分隔的地址。

Now the "toAddress" string that my function recieves might contain a single address, or it might have many, comma delimited addresses.

现在的问题是,在使用多个逗号分隔的地址的情况下,其中一个或两个可能使用了错误的电子邮件地址格式。

Now the problem is that, in case of multiple comma delimited addresses, one or two of them might be of the wrong email address format.

因此,当我尝试使用此代码发送电子邮件时,出现异常:

So when I try to send an email using this code, I get the exception:

字符串不是电子邮件地址所需的格式。

"The specified string is not in the form required for an e-mail address."

有什么方法可以验证逗号分隔的电子邮件地址吗?
我在某处读到,验证电子邮件地址的唯一方法是向其发送电子邮件,因为验证电子邮件地址的正则表达式可能会非常庞大​​。

Is there any way to validate the comma delimited email addresses? I had read somewhere that the only way to validate an email address is to send an email to it, because the regular expressions to validate an email addreess can be surprisingly huge.

此外,我无法控制设计,也无法控制该地址字符串如何进入我的函数,我无法在UI中添加电子邮件验证,因此我无能为力...

Also, I have no control over the design, or on how that address string comes to my function,I can't add the email validation in the UI, so I am helpless there...

我的问题是,即使邮件中的 SOME ,电子邮件也不会传递给以逗号分隔的字符串中的地址 ALL 地址格式错误。

My problem is that the email will not be delivered to ALL the addresses in the comma delimited string, even though only SOME of the addresses are of the wrong format.

有什么方法可以正确验证.NET中的电子邮件地址?有没有办法清除不良的电子邮件地址,然后仅将邮件发送给优质的电子邮件地址?

Is there any way to properly validate email addresses in .NET? Is there a way to weed out the bad email addresses and send the mail to only the good ones?

推荐答案

您可以拆分逗号中的电子邮件字符串,并使用简单(或巨大)的电子邮件正则表达式验证每个电子邮件地址。或者,尝试创建 MailAddress 对象;它也支持地址的一些基本验证。

You could just split the email string on the comma and validate each email address using a simple (or huge) email regex. Or, try creating a MailAddress object; it supports some basic validation of the address too.

这篇关于验证电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆