使用 SSH.NET 从 SFTP 服务器附加文件到 MailMessage

Attach file from SFTP server using SSH.NET to MailMessage

有没有办法让它工作?

我们正在从 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);
                }
            }
        }
    }
}

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

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