c# - 发送包含相同附件的多封电子邮件

标签 c# email

我想使用 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/

相关文章:

macos - 使用 Applescript 设置 "Reply-To"地址

python - 通过 python 通过电子邮件发送 mysql select 语句

javascript - 通过sendgrid发送邮件到某些邮箱出来中文了

php - AWS SES SMTP 电子邮件有效。 AWS SES API 不发送电子邮件

html - 邮件页脚签名中的 MsoNormal。如何去除?

c# - 使用 AE.NET 从 gmail 获取附件不起作用

c# - Linq to Sql 设计和 MVP

c# - 你如何组织你的支持领域? (样式/图案)

c# - 尽管计算机进入待机模式,Window 应用程序能否继续运行?

c# - 我正在编写必须在 Windows 和 Linux(在单声道下)上运行的 C# 代码。处理两者文件路径的简单方法?