How do I send an email to an address with a dash in it?
Asked Answered
A

2

7

Is it me or is there a bug in the MailAddress class in System.Net.Mail?

This code will always throw an excpetion:

MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");     
mail.To.Add("[email protected]");

mail.Subject = "Test email"
mail.IsBodyHtml = true;
mail.Body = "<b>Does not work</b>";

//Connect to server and send message.               
SmtpClient smtp = new SmtpClient();
smtp.Host = "mailserver.me.com";
smtp.Send(mail);

The exception I get is this:

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

However, according to wiki, a dash is a valid character in the local part.

Does anyone know a way of using the System.Net.Mail classes to send an email to someone with a dash in the email address?

Attalie answered 6/11, 2010 at 4:9 Comment(1)
@Mitch Wheat : good comment. I was thinking "can anyone else replicate this?"Calefaction
P
2

Are you sure? It works for me (I cut and paste your code replacing your dummy mail server with my actual mail server.) I just get delivery notifications that the message to [email protected] is undeliverable.

Since you have an exception message, I guess it's real. Is it possibly an encoding issue?

Pastis answered 6/11, 2010 at 4:26 Comment(2)
Thanks for your comment... It made me look a little deeper... It seems every email address I was reading in from the DB had \r at the end of it, thus throwing the error.Attalie
@thorkia: Ah, okay. Good. It had to be something like that.Pastis
K
0

This exception can be caused by having an invalid email address in the from attribute of the smtp element of the app.config file. Although that would cause any attempt to send email to throw an exception, regardless of whether the to email address contained a dash or not. Nevertheless, it is worth checking what is specified in the mailSettings element of app.config.

Kazue answered 6/11, 2010 at 10:45 Comment(2)
are you saying that that the app.config settings override the code settings (as @Attalie coded, above)?Calefaction
@Calefaction - No, I’m not saying that. But if there is an invalid email address in the ‘from’ attribute, it will generate the exception, even though you apparently subsequently set a valid ‘from’ email address via code. If by mistake, @Attalie had for example, from=”me” in his app.config then he would have generated the exception. In this case, the exception would have been thrown at the time the MailMessage object was created, i.e. before the code to set the valid ‘from’ email address executed.Kazue

© 2022 - 2024 — McMap. All rights reserved.