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