0

我正在向超过 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);

            }
4

1 回答 1

0

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

FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));
于 2013-10-25T17:15:50.487 回答