发送包含相同附件的多封电子邮件
本文关键字:电子邮件 包含相 | 更新日期: 2023-09-27 18:12:17
我想使用for循环发送包含相同pdf文档的多封电子邮件,现在第一个电子邮件地址总是收到电子邮件,但随后的电子邮件地址出现错误'进程无法访问文件'file'path'file.pdf',因为它正在被另一个进程使用。
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;
}
您需要处置您的MailMessage
(这也将处置附件)。
using (var mail = new MailMessage()) {
//yourcode
}
你可以看看这个
其他解决方案
另一种方法是在循环之前创建您的mailmessage,在循环中添加新的To
地址,并在循环之后发送。
这取决于你是想发送一条还是多条消息