tags:

views:

313

answers:

2

Hi,

Am trying to asynchronously send an email with an attachment using .net's SMPTClient class:

SmtpClient smtp = new SmtpClient(MailServer);

                smtp.SendAsync(mailMsg, ""); 

                smtp.SendCompleted += new SendCompletedEventHandler(MailSentCallback);

                mailMsg.Dispose();

I need to delete the attachment file from my server as soon as the mail is successfully sent.

  private static void MailSentCallback(object sender, AsyncCompletedEventArgs e)
        {
           File.Delete(myAttachment);
        }

But when this method is called, am getting an error: "The process cannot access the file 'myAttachment' because it is being used by another process." Also, mail is not being delivered.If i use Send method instead of SendAsync, then mail delivery is working.

What am i missing here?

Thanks for reading!

+1  A: 

Firstly you should wire up the SendCompletedEventHandler BEFORE you do the SendAsync. ie:

//Wire up SendCompetedEventHandler
smtp.SendCompleted += new SendCompletedEventHandler(MailSentCallback);
//Send the Message
smtp.SendAsync(mailMsg, "");

Secondly where is myAttachment declared? What is its scope?

mundeep
thanks for ur input mundeep!
Steve Chapman
+1  A: 

Okay, first of all, as mundeep says, connect the event handler before the SendAsync call.

Also, do not Dispose() the message where you do, because at that point it may not have been 'sent' yet... you're basically potentially corrupting the message while the SmtpClient is trying to process it.

Now, as to your actual problem, I had the same problem, and from memory the file is still being held by the SmtpClient during the callback, so you really cannot delete it. I think attaching a file in the filesystem is really best only used if this is a persistent file.

If you are trying to send a temporary file, load it into a MemoryStream, and create an Attachment from that.

It just occurs to me that maybe you can solve the attachment deletion problem by first disposing of the Attachment object in your callback handler, before trying to delete the file... although I'd very carefully test that this does not cause other side effects.

jerryjvl
thanks jerryjvl...!am now using Memorystream and attaching it to mail message on the fly....works like a charm without any "file is being used by other process" errors...thanks again!
Steve Chapman