1

I want to send multiple emails containing the same pdf document using a for loop, now the first email address always recieves the email but then an error occurs for the follwing email addresses `The process cannot access the file 'file\path\file.pdf' because it is being used by another process.

 foreach (GridViewRow Row in GridView1.Rows)
            {
                           MailMessage mail = new MailMessage();
                                SmtpClient SmtpServer = new SmtpClient(smtpServer);
                            mail.From = new MailAddress(Sender);
                            mail.To.Add(new MailAddress(to));
                            mail.Subject = Subject;
                            mail.Body = TextBox2.Text;

                            Attachment attachment;
                            attachment = new Attachment(Server.MapPath("~/temp/file.pdf"));
                            mail.Attachments.Add(attachment);
                            SmtpServer.Port = SmtpPort;
                            SmtpServer.Credentials = new System.Net.NetworkCredential(Sender, Password);
                            SmtpServer.EnableSsl = true;
                            try
                            {
                                SmtpServer.Send(mail);
                                sent++;
                            }
                            catch (Exception ex)
                            {
                                Label1.Visible = true;
                                Label1.Text = ex.Message.ToString();
                                if (ex.InnerException != null)
                                {
                                    Label1.Text = ex.InnerException.ToString();
                                    Label1.Visible = true;
                                }
                            }
                            Label2.Text = "Sent: " + sent + "Failed: " + failed + " Without Email:" + NoEmail;
                            Label2.Visible = true;
}
Sibusiso Shongwe
  • 176
  • 1
  • 2
  • 21

1 Answers1

3

You need to dispose your MailMessage (which will dispose the attchments too).

Easy fix

using (var mail = new MailMessage()) {
 //yourcode
}

You may take a look at this

Other solution

Another way could be to just create your mailmessage before the loop, add the new To addresses in the loop, and send it after the loop.

Depends if you wanna send one or many messages.

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • thanks guys but the fix is not helping me, am now a receiving a `System.IO.IOException: Authentication failed because the remote party has closed the transport stream.` error but the first one still sends – Sibusiso Shongwe Oct 10 '16 at 14:47