【问题标题】:Attach file from SFTP server using SSH.NET to MailMessage使用 SSH.NET 将文件从 SFTP 服务器附加到 MailMessage
【发布时间】:2022-01-01 17:01:10
【问题描述】:

有没有办法让它工作?

我们从 SFTP 服务器获取文件,作为 CRON 自动化作业的一部分,我们需要将其通过电子邮件发送给某人。

这是我所拥有的,但我无法将文件作为附件发送。

string host = @"scp.test.com";
string username = "test";
string password = "test";
string localFileName = System.IO.Path.GetFileName(@"localfilename");
string remoteDirectory = "/home/test/";

using (var sftp = new SftpClient(host, 65000, username, password))
{
    sftp.Connect();
    var files = sftp.ListDirectory(remoteDirectory);

    foreach (var file in files)
    {
        if (!file.Name.StartsWith("."))
        {
            string remoteFileName = file.Name;

            using (SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"))
            {
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress("test@gmail.com");
                    mail.To.Add("test@test.co.za");
                    mail.Subject = "Test Mail - 1";
                    mail.Body = "Mail with attachment";
                    mail.IsBodyHtml = false;
                    // Cannot convert SFTP file to Attachment
                    mail.Attachments.Add(file);

                    SmtpServer.Port = 587;
                    SmtpServer.UseDefaultCredentials = false;
                    SmtpServer.Credentials =
                        new System.Net.NetworkCredential("test", "test");
                    SmtpServer.EnableSsl = true;

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

【问题讨论】:

    标签: c# smtp sftp ssh.net mailmessage


    【解决方案1】:

    使用SftpClient.OpenRead获取远程文件内容的“Stream”接口,construct an Attachment using it

    using (var fs = sftp.OpenRead(file.FullName))
    {
        // ...
        mail.Attachments.Add(new Attachment(fs, file.Name));
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      相关资源
      最近更新 更多