Partilhar via


"Object reference not set to an instance of an object" error when trying to create object of System.Net.Mail.MailMessage

A few days ago I ran into an interesting problem. A customer who was trying to send a mail using System.Net.Mail was getting the error "Object reference not set to an instance of an object" when trying to create a Instance of the MailMessage class.

Code that was failing

 MailMessage message = new MailMessage()

The strange thing was that if I used any other variant of the constructor for MailMessage everything worked.

Code that worked

 MailMessage message = new MailMessage("a@a.com", "a@a.com", "Test Message", "Test Message")
MailMessage message1 = new MailMessage("a@a.com", "a@a.com")

What could be the difference?

Debugging the System.Net.Mail source using Visual Studio 2008 we found the following difference:

When the default constructor is used, the below is the code for the MailMessage constructor:

 public MailMessage() {
            message = new Message(); 
            if(Logging.On)Logging.Associate(Logging.Web, this, message); 

            // This call below is what I am talking about.  
            string from = SmtpClient.MailConfiguration.Smtp.From; 

            if (from != null && from.Length > 0) { 
                message.From = new MailAddress(from);
            } 
        }

In the above code there is a call to read the "from" address from the mail configuration. This call is not there in any of the other constructors and therefore the other constructors work.

What is causing "string from = SmtpClient.MailConfiguration.Smtp.From"  line to fail? The code is trying to read some setting from a configuration file. There is no web.Config or app.config file, then where is it trying to read from?

The code tries to read from the machine.config and trying to get the mailSettings section. Is the mailSetting section not there?

The mailSettings section was present but there was a typo in the name which the customer had accidentally made. It was typed as "mailfSettings". Correcting the spelling fixed the problem.

 

Enjoy!