-2

Hellow, I`ve tried to create a pdf files and send them at the same time in a loop to different email address, but it seems the first created file doesnt close to allow the next one to be created, i use the same name (overwriting the file).

here is the code for attaching the email

private void sendEmail(string email)
    {
        sendInfo = new Label();
        sendInfo.Font = new Font("Calibri", 11);


        sendInfo.AutoSize = true;

        MailMessage mail = new MailMessage("ikwabe04@gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante.");
        SmtpClient client = new SmtpClient("smtp.gmail.com");
        client.Port = 587;

        client.Credentials = new System.Net.NetworkCredential("ikwabe04@gmail.com", "mikunjoyamwili");
        client.EnableSsl = true;

            Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf");
            file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
            mail.Attachments.Add(file);

        try
        {
            client.Send(mail);
            Login.RecordUserActivity("Sent the Salary Slip to " + email);

            sendInfo.ForeColor = Color.LightGreen;
            sendInfo.Text = "Email sent to: " + email + "     (" + DateTime.Now.ToLongTimeString() + ")";
            information.Controls.Add(sendInfo);
        }
        catch
        {
            sendInfo.ForeColor = Color.Orange;
            sendInfo.Text = "Email NOT sent to: " + email + "     ("+DateTime.Now.ToLongTimeString()+")";
            information.Controls.Add(sendInfo);
        }


    }

here code to create a pdf

using (FileStream file = new FileStream("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                PdfWriter.GetInstance(pdfDoc, file);
            pdfDoc.Open();
            pdfDoc.Add(table);
            pdfDoc.Add(slp);
            pdfDoc.Add(Separator);

            pdfDoc.Add(table1);
            pdfDoc.Add(Separator);
            pdfDoc.Add(Tsh);
            pdfDoc.Add(incomeTitle);
            pdfDoc.Add(incomeTable);
            pdfDoc.Add(totaInc);
            pdfDoc.Add(taxDeductionTitle);
            pdfDoc.Add(taxDeduction);
            pdfDoc.Add(otherDeductionTitle);
            pdfDoc.Add(OtherDeduction);
            pdfDoc.Add(totaDeduc);
            pdfDoc.Close();
            file.Close();
        }

here is the code for sending email

for (int i = 0; i< table.Rows.Count;i++)
{
    PreapareSalarySlip(table.Rows[i][2].ToString(),
                       table.Rows[i][3].ToString(),
                       table.Rows[i][5].ToString(),
                       table.Rows[i][37].ToString()
                       );


                 sendEmail(table.Rows[i][38].ToString());      
                }

here is the Error occured An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\Shadrack Ikwabe\AppData\Roaming\SEC Payroll\Receipts\receipt.pdf' because it is being used by another process.

Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39

1 Answers1

1

It isn't the PDF creation process that is locking the file. It's the attachment. The Attachment class locks the file and doesn't release the lock until it is disposed. You're getting the exception because you're trying to attach the same file to two different emails without releasing the lock by disposing of the attachment.

SmtpClient and MailMessage are also disposable. Disposing of the MailMessage is sufficient; when it is disposed, it also disposes its attachments. However, I consider it better to make it explicit.

You should be disposing of them properly using a using:

using (MailMessage mail = new MailMessage("ikwabe04@gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante."))
using (SmtpClient client = new SmtpClient("smtp.gmail.com"))
using (Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf"))
{
    client.Port = 587;
    client.Credentials = new System.Net.NetworkCredential("ikwabe04@gmail.com", "mikunjoyamwili");
    client.EnableSsl = true;      

    file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
    mail.Attachments.Add(file);
    try
    {
        client.Send(mail);
        Login.RecordUserActivity("Sent the Salary Slip to " + email);

        sendInfo.ForeColor = Color.LightGreen;
        sendInfo.Text = "Email sent to: " + email + "     (" + DateTime.Now.ToLongTimeString() + ")";
        information.Controls.Add(sendInfo);
    }
    catch
    {
        sendInfo.ForeColor = Color.Orange;
        sendInfo.Text = "Email NOT sent to: " + email + "     ("+DateTime.Now.ToLongTimeString()+")";
        information.Controls.Add(sendInfo);
    }
}