我想使用 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
}
你可以看看this
其他解决方案
另一种方法是在循环之前创建您的邮件消息,在循环中添加新的 To
地址,并在循环之后发送它。
取决于您是想发送一条消息还是多条消息。
关于c# - 发送包含相同附件的多封电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39960426/