【问题标题】:Sending multiple emails containing the same attachment发送包含相同附件的多封电子邮件
【发布时间】:2017-02-19 00:03:00
【问题描述】:

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

【问题讨论】:

  • 请贴出相关代码
  • 听起来您要么不处理文件,要么不处理第一封电子邮件中的 MailAttachment
  • 刚刚添加了代码

标签: c# email


【解决方案1】:

您需要处置您的MailMessage(这也会处置附件)。

轻松修复

using (var mail = new MailMessage()) {
 //yourcode
}

你可以看看this

其他解决方案

另一种方法是在循环之前创建您的邮件消息,在循环中添加新的To 地址,然后在循环之后发送。

取决于您是要发送一条消息还是多条消息。

【讨论】:

  • 谢谢大家,但修复对我没有帮助,现在收到 System.IO.IOException: Authentication failed because the remote party has closed the transport stream. 错误但第一个仍然发送
猜你喜欢
  • 2015-10-13
  • 2014-11-26
  • 2011-07-14
  • 2011-02-08
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
相关资源
最近更新 更多