6

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("me@me.com");     
mail.To.Add("joe-blow@me.com");

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?

thorkia
  • 1,972
  • 1
  • 20
  • 26

2 Answers2

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 joe-blow@me.com is undeliverable.

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

jason
  • 236,483
  • 35
  • 423
  • 525
  • 3
    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. – thorkia Nov 06 '10 at 14:22
  • @thorkia: Ah, okay. Good. It _had_ to be something like that. – jason Nov 07 '10 at 23:01
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.

Mike Green
  • 2,031
  • 2
  • 18
  • 16
  • are you saying that that the app.config settings override the code settings (as @thorkia coded, above)? – Pure.Krome Nov 06 '10 at 12:14
  • @Pure.Krome - 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, @thorkia 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. – Mike Green Nov 07 '10 at 09:02