如何在 C# 中循环邮件附件时释放文件锁定

本文关键字:释放 文件 锁定 文件锁 循环 | 更新日期: 2023-09-27 18:36:51

我正在向超过 1 个人发送单封邮件。 所以我在带有附件的 for 循环中发送邮件。但是在第二个循环中,我收到文件锁定错误。下面是我的代码。

public string SendMail(string toList, string from, string ccList,
string subject, string body)
{
    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
    SmtpClient smtpClient = new SmtpClient();
    string msg = string.Empty;

    try
    {
        MailAddress fromAddress = new MailAddress(from);
        message.From = fromAddress;
        message.To.Add(toList);
        if (ccList != null && ccList != string.Empty)
            message.CC.Add(ccList);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = body;
        // We use gmail as our smtp client
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new System.Net.NetworkCredential(TextBox1.Text, TextBox2.Text);
    if (FileUpload2.HasFile)
    {
        // File Upload path
        String FileName = FileUpload2.PostedFile.FileName;

        FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));

        //Getting Attachment file
        Attachment mailAttachment = new Attachment(Server.MapPath(FileName));
        //Attaching uploaded file
        message.Attachments.Add(mailAttachment);
    }   
        smtpClient.Send(message);
        LblMessage.ForeColor = System.Drawing.Color.Green;
        LblMessage.Text = "Mail Sent Successfully.";
    }
    catch (Exception ex)
    {
        LblMessage.Text = ex.Message;
        LblMessage.ForeColor = System.Drawing.Color.Red;
    }
    return msg;
}

在循环中调用此函数

for (int i = 0; i < LbEmails.Items.Count; i++)
            {
                SendMail(LbEmails.Items[i].ToString(), TextBox1.Text, "", TbSubject.Text, TbBody.Text);
            }

如何在 C# 中循环邮件附件时释放文件锁定

看起来您为发送的每封电子邮件保存一次上传的文件,即使所有电子邮件似乎都相同。从 SendMail() 方法中提取此行,并在循环之前调用它:

FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));