We’re getting reports of occasional out-of-memory issues reported during SMTP sending. We’re careful to call Dispose on our SmtpClient but we’ve made no effort to call Dispose on each MailMessage used to compose and send a message. Does that cause a memory leak?
Hello @cp60299,
Even though you are disposing of the SmtpClient, it does not dispose of the MailMessage instances you create and send.
The MailMessage class implements the IDisposable interface, which means it may holds resources that need to be released.
You can enclose the SmtpClient and MailMessage in using statements, ensuring that their Dispose methods are called automatically:
using (var client = new SmtpClient(...))
{
using (var eml = new MailMessage(...))
{
...
client.Send(eml);
}
}
Thanks Margarita. We’ll change our code to dispose the MailMessage instances we create. Does not doing this cause a memory leak? And when receiving, do we need to dispose the MailMessage instances we get access to using Pop3Client.FetchMessage, and IEWSClient.FetchMessage? And what about the ExchangeMessageInfo instances we get from IEWSClient.ListMessages?
- Dispose of MailMessage instances retrieved via Pop3Client.FetchMessage and IEWSClient.FetchMessage.
- No need to dispose of
ExchangeMessageInfo
instances if the message does not contain attachments.