通过迭代将多个附件从光盘添加到电子邮件

Ole*_*e M 5 c# loops

更新我用 Excel 文档而不是 PDF 对此进行了测试,并且它有效。为什么它不能与 PDF 一起使用?

我试图通过迭代文件路径字符串列表来向电子邮件添加 X 个附件。相反,我收到了 X 个附件,但它们都是同一文件的副本。因此,附件的数量是正确的,但其内容却不正确。

即使这样也会发生:

  1. PDF 文件已正确保存在磁盘上。
  2. 调试时,文件路径列表是正确的。
  3. 调试时,文件名和文件路径是不同的。

我正在使用FluentEmail发送电子邮件。另外,我基于以下示例(请参阅“多个附件”部分)。

我添加Debug.WriteLine(path)只是为了检查我是否能够正确输出循环中的字符串,我就是这样。

我的方法:

public async void SendInvoicesEmail() {

    try {

        using (SqlConnection con = new(ConnectionString.connectionString))
        using (SqlCommand cmd = new("query text", con)) {

            con.Open();

            SmtpSender sender = new SmtpSender(() => new SmtpClient(host: "smtp.office365.com") {

                EnableSsl = true,
                UseDefaultCredentials = false,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("email", "password"),
                Port = 587
            });

            Email.DefaultSender = sender;
            IFluentEmail newEmail = Email
                .From("email")
                .To("email")
                .Subject("subject text")
                .Body("body text");

            var attachList = new List<FluentEmail.Core.Models.Attachment>();

            // SourcePathList contains all the file paths I need to reference.
            foreach (string path in SourcePathList) {

                string fileName = Path.GetFileName(path);

                var attachment = new FluentEmail.Core.Models.Attachment {

                    Data = File.OpenRead(path),
                    ContentType = "application/pdf",
                    Filename = $"{fileName}"
                };

                attachList.Add(attachment);
                Debug.WriteLine(path);
            }

            newEmail.Attach(attachList);
            SourcePathList.Clear();
            FluentEmail.Core.Models.SendResponse result = await newEmail.SendAsync();

            if (result.Successful) {

                cmd.ExecuteNonQuery();
            }
        }

    } catch (Exception ex) {

        MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
    }
}
Run Code Online (Sandbox Code Playgroud)

我努力了:

  1. 使用newEmail.AttachFromFilename
  2. 使用newEmail.Send而不是.SendAsync.
  3. 迭代数组而不是列表。
  4. 更改了我的 SMTP 主机。
  5. 尝试使用ContentType较旧的 PDF(即使我已经更新了软件):"application/x-pdf".

但以上这些都没有任何区别。

在此输入图像描述

存在的三个项目是不同的,但只有最后一个项目作为文件添加到 3 个附件中。确实很ContentId重要?

Pan*_*mar 2

我认为流对象没有在循环中刷新,并且它为每个附件添加相同的文件内容。
您应该在 using 语句中使用流对象,如下所示

我也在我的网站上使用类似的功能System.Net.Mail

早些时候我建议了一个未经测试的代码,它有一个错误。现在我再次测试了您的代码,它按预期工作。这是我在 MVC 控制器中运行的完整方法。

public async void SendInvoicesEmail()
        {
            try
            {
                SmtpSender sender = new SmtpSender(() => new SmtpClient(host: "smtp.sendgrid.net")
                {

                    EnableSsl = true,
                    UseDefaultCredentials = false,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential("user", "password"),
                    Port = 587
                });

                Email.DefaultSender = sender;
                IFluentEmail newEmail = Email
                    .From("Admin@admin.com")
                    .To("user@user.com")
                    .Subject("I am feeling lucky")
                    .Body("This email is for stack overflow problem solution.");

                var attachList = new List<FluentEmail.Core.Models.Attachment>();
                // SourcePathList contains all the file path on my machine.
                var SourcePathList = new List<string>
                {
                    "C:\\Consolidate_09122021085902.xlsx",
                    "C:\\PaySlip_15022022075604.xlsx",
                    "C:\\RateCard_14022022104134.xlsx"
                };
                
                foreach (string path in SourcePathList)
                {

                    string fileName = Path.GetFileName(path);
                    var attachment = new FluentEmail.Core.Models.Attachment
                    {

                        Data = System.IO.File.OpenRead(path),
                        ContentType = "application/pdf",
                        Filename = $"{fileName}"
                    };

                    attachList.Add(attachment);
                    Debug.WriteLine(path);
                }

                newEmail.Attach(attachList);
                SourcePathList.Clear();
                FluentEmail.Core.Models.SendResponse result = await newEmail.SendAsync();

            }
            catch (Exception ex)
            {
                // write log file
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是电子邮件输出

在此输入图像描述