【问题标题】:Cannot convert from 'string[]' to 'System.Net.Mail.Attachment' [duplicate]无法从“字符串 []”转换为“System.Net.Mail.Attachment”[重复]
【发布时间】:2019-06-14 19:40:25
【问题描述】:

我正在尝试向通过我的程序发送的电子邮件添加附件,但我收到了上面提到的错误。
我正在保存运行时拍摄的图像,并将名称添加到名为 ImageFilenames 的列表中。然后,我使用以下代码检索文件并将它们添加为附件,但我似乎无法弄清楚我需要做什么才能使其正常工作。

            SaveScreenshots();

            using (MemoryStream stream = new MemoryStream())
            {
                using (SmtpClient SmtpServer = new SmtpClient())
                {
                    using (MailMessage mail = new MailMessage())
                    {
                        mail.From = new MailAddress("*****.******@******.com");
                        mail.To.Add("******@*****.com");
                        mail.Subject = this.Summary;
                        mail.Body = this.ToString();

                        SmtpServer.Port = ***;

                        foreach (string file in ImageFilenames)
                        {
                            var images = Directory.GetFiles(file);

                            mail.Attachments.Add(images); 

 //I tried this and the below method with no success

                            mail.Attachments.Add(Directory.GetFiles(file));
                        }

                        SmtpServer.Credentials = new System.Net.NetworkCredential("******@****.com", "********");
                        SmtpServer.EnableSsl = false;
                        SmtpServer.Host = "*****-1";

                        SmtpServer.Send(mail);
                    }
                }
            }
        }
        ClearScreenCaptures();

    }

任何帮助将不胜感激。谢谢!

编辑:感谢您提出相关问题,但我知道如何添加附件。我的问题具体是如何使用文件名列表来做到这一点。不过还是谢谢!

【问题讨论】:

  • 你已经有了答案。您不能将字符串添加到附件集合中,您需要为从 getFiles() 返回的每个文件创建附件

标签: c# visual-studio


【解决方案1】:
Directory.GetFiles(file);

返回一个字符串数组,您需要创建一个附件对象。像这样的:

var attachment = new Attachment(filePath));

【讨论】:

  • 谢谢!这是我缺少的部分,现在看起来很明显。现在正在运行,非常感谢您的帮助!
  • np - 很高兴能提供帮助
【解决方案2】:

试试这个

 Directory.GetFiles(file).ToList()
     .ForEach(t =>  x.Attachments.Add(new Attachment(t)));

【讨论】:

    猜你喜欢
    • 2019-05-11
    • 2017-08-17
    • 2013-01-12
    • 2017-01-31
    • 2023-03-28
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2014-04-18
    相关资源
    最近更新 更多