Sibusiso Shongwe
Sibusiso Shongwe

Reputation: 175

Sending multiple emails containing the same attachment

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;
}

Upvotes: 1

Views: 495

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

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.

Upvotes: 3

Related Questions