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?
This is code we have on production (even added a comma for you). Normally you shouldn't use try/catch for validation, but it works well here. I believe it's better than trying to recode the validator.
string[] allToAddresses = to.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) foreach (string toAddress in allToAddresses) { try { message.To.Add(toAddress); } catch (FormatException) { //do nothing, ill-formed address. } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With