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>
instead of placing the
MailMessageas the subject of theusingblock, try making theSmtpClientthe 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
usingblock also represents the body of an instance method, a naive test could be:Create an instance of the containing class
Send the first message via a call to the above-referenced class method
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.Timeoutvalue to2– see his comment for more on this.Create a new instance of that same class
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.