1

I have trouble with sending an email with attached file in C#. First time everything is ok: a pdf file is generated and attached to a email and the email can be send and receive. But if I try this twice, I get an IO-Exception when generating the file. If I try to rename the file manually I get an error message, which show me that the IIS Worker Process keep on using the file.

If I commented the part for email sending out, the file can generated and saved more times. So it's sure that the error is in this code part.

Here is my code for sending the email:

MailMessage eMail = new MailMessage();
eMail.To.Add(sEmailAddressReceiver); //filled before
eMail.From = new MailAddress(sEmailAddressSender); //filled before
eMail.Subject = "Title";
eMail.Priority = MailPriority.Normal;
eMail.Body = "File is attached.";
Attachment aAttachment = new Attachment(sFilename);
eMail.Attachments.Add(aAttachment);
SmtpClient smtpClient = new SmtpClient("xxx", 25);
smtpClient.Send(eMail);

Have anyone an idea what is missing?

Thank you!

Stefan
  • 17,448
  • 11
  • 60
  • 79
  • Where is the code "generating" the file? If the file is coming from the code itself then do you even need to keep it on the file system or can you just attach it as a byte stream? – David Nov 13 '13 at 11:11
  • Thank you, the Dispose-Method is the solution I searched for! Sorry for duplicating, it is difficult to search like someone describes even if I don't know how the describtion is ;). – user2987333 Nov 13 '13 at 13:36

1 Answers1

3

For starters, try to use Dispose() on the disposable objects.

You can do this implicit with the using statement. Or by explicit calling Dispose()

using (MailMessage eMail = new MailMessage())
{
      eMail.To.Add(sEmailAddressReceiver); //filled before
      eMail.From = new MailAddress(sEmailAddressSender); //filled before
      eMail.Subject = "Title";
      eMail.Priority = MailPriority.Normal;
      eMail.Body = "File is attached.";

      using (Attachment aAttachment = new Attachment(sFilename))
      {  
          eMail.Attachments.Add(aAttachment);
          using (SmtpClient smtpClient = new SmtpClient("xxx", 25))
          {
               smtpClient.Send(eMail);
          }
      }
}
Stefan
  • 17,448
  • 11
  • 60
  • 79
  • 1
    Thank you very much! I added these two lines: eMail.Dispose(); smtpClient.Dispose(); after the line "smtpClient.Send(eMail);" Now I can generated several emails and it works great! – user2987333 Nov 13 '13 at 13:29