Search code examples
c#smtpsftpssh.netmailmessage

Attach file from SFTP server using SSH.NET to MailMessage


Is there a way to get this working?

We are getting a file from an SFTP server and we need to email it to someone as part of a CRON automation job.

Here is what I have, but I cannot send the file as an attachment.

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("[email protected]");
                    mail.To.Add("[email protected]");
                    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);
                }
            }
        }
    }
}

Solution

  • Use SftpClient.OpenRead to obtain "Stream" interface to the remote file contents, and construct an Attachment using it:

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