1

I am trying to send email using the following code and get the error above.

There is two emails being sent the first one seems to get delivered fine, the code below doesn't seem to work.

Can anyone help please?

        using (var mail = new MailMessage(fromEmail.Trim(), ToEmail.Trim()))
        {
            mail.IsBodyHtml = true;

            bodyText = bodyText.Replace("**Message**", Message);

            // populate the message
            mail.Subject = subject;
            mail.Body = bodyText;

            // send it
            var smtpClient = new SmtpClient();
            smtpClient.Send(mail);
        }

The config:

  <system.net>
    <mailSettings>
      <smtp from="test@foo.com">
        <network defaultCredentials="true" port="25" host="127.0.0.1" password="" userName=""/>
      </smtp>
    </mailSettings>
  </system.net>
Burt
  • 7,680
  • 18
  • 71
  • 127

1 Answers1

3

instead of placing the MailMessage as the subject of the using block, try making the SmtpClient the subject.

EDIT: If your version of .net is < 4.0, you will need to do some finagling to ensure that the smtp client is disposed before attempting to send another message.

Assuming that the using block also represents the body of an instance method, a naive test could be:

  1. Create an instance of the containing class

  2. Send the first message via a call to the above-referenced class method

  3. Set the reference = null (in other words, ensure that the SmtpClient has actually been marked/disposed. You may want/need to manually dispose of the instance as a further check)

    Jeff Tucker made the suggestion that you set the SmtpClient.Timeout value to 2 - see his comment for more on this.

  4. Create a new instance of that same class

  5. Send the second message

Following that (assuming that works), you can iterate the steps to refine and narrow the logic until you're satisfied with it.

Community
  • 1
  • 1
Josh E
  • 7,390
  • 2
  • 32
  • 44
  • 2
    MailMessage and SmtpClient both implement IDisposable in .Net 4, so both should have usings. Of the two though, SmtpClient is the more important one to properly dispose. – hatchet - done with SOverflow Jul 12 '12 at 18:38
  • Smtp doesn't implement IDisposable in the version of the framework I am targeting. Any ideas? – Burt Jul 12 '12 at 18:39
  • 2
    Set SmtplClient.Timeout value to 2, this will cause the connection to be destroyed (probably) after you send the first email message and force a new connection to be added to the connection pool. The reason you should use 2 is because of a bug (fixed in .NET 4) that made values of 1 and 0 actually be infinity. Smtp connections are pooled independently of SmtpClient objects so setting it to null or trying to manually dispose of it won't work (and it has no Dispose method prior to 4.0). – Jeff Tucker Jul 12 '12 at 19:15