Learning While Aging

Exception error when instantiating MailMessage instance

When instantiating an instance of the MailMessage class:

'VB.NET
Dim mm As MailMessage = new MailMessage()
//C#
MailMessage mm = new MailMessage();

you get an exception error:

The specified string is not in the form required for an e-mail address.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in
the code.

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

What is the problem?
Let’s take a look at the MailMessage constructor on MSDN web site: http://msdn.microsoft.com/en-us/library/ms144707(VS.80).aspx, especially pay attention to the Remarks section:

Oh, I see, if you have the following mailSettings in web.config file:

<system.net>
  <mailSettings>
    <smtp from="localhost">
     <network host="localhost" password="!password!" userName=user@mysite.com/>
    </smtp>
  </mailSettings>
</system.net>

Then the MailMessage constructor will set From to be the value of “from” in <mailSettings>. In this case, where from=”localhost” does not contain a valid email address, it throws FormatException error as mentioned above.

Therefore, if you define <mailSettings> in web.config, make sure “<smtp from=” is assigned to a valid email address, or at least in a valid email format.