For anyone that is writing code to send mail with SMTP and attaching a file or files......remember the next piece of advise.
The Normal Code:
try
{
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
message.Attachments.Add(@"C:\temp\test.doc");
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(txtSMTPUser.Text, txtSMTPPass.Text);
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = SMTPUserInfo;
emailClient.Send(message);
litStatus.Text = "Message Sent";
}
catch (Exception ex)
{
litStatus.Text = ex.ToString();
}
Problem:
If you try and delete "C:\temp\test.doc" after sending the email, you will get a IO exception because the file is still being used by a process.
I battled for four hours thinking that the Thread I was running is what was holding the file, but it wasn't.
After alot of searching I realised my mistake, knocked my head on the table a couple of times and fixed my idiotic error.
To release the file for deletion you have to dispose of the attachments after "emailClient.Send(message);":
message.Attachments.Dispose();
In all normal examples they never tell you to do this, but I will from now on make it a habit to dispose the attachments after sending the email and setting message & emailClient to null
Hope it helped someone.
What not...if not.
Software is never finished and can always be improved.