c#email格式不正确,验证在C#中的电子邮件地址

博客讨论了在C#中使用SMTP发送邮件时遇到的问题,特别是当收件人地址可能包含多个逗号分隔的电子邮件地址,其中一些可能是无效格式时。作者提出可以将邮件地址字符串按逗号分割并分别验证每个地址,或者尝试创建MailAddress对象进行基本验证。同时,提出了使用正则表达式或通过尝试创建邮箱对象来过滤无效地址的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

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.

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...

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.

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值