Skip to content

Instantly share code, notes, and snippets.

@jyunderwood
Created June 18, 2018 14:48
Show Gist options
  • Save jyunderwood/546b28dca3d6329b56e1021573988a16 to your computer and use it in GitHub Desktop.
Save jyunderwood/546b28dca3d6329b56e1021573988a16 to your computer and use it in GitHub Desktop.
SCP and Email a file
using Renci.SshNet;
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.IO;
using System.Linq;
namespace PlayBall
{
internal class Program
{
private static void Main(string[] args)
{
var _sendGridApiKey = "";
Console.WriteLine("Connecting...");
using (var sftpClient = new SftpClient("server", "user", new PrivateKeyFile("rsa.key")))
{
sftpClient.Connect();
var files = sftpClient.ListDirectory("/directory");
var mostRecentFile = files.OrderByDescending(f => f.Name).FirstOrDefault();
if (mostRecentFile == null)
{
Console.WriteLine("Failed to get most recent file.");
return;
}
Console.WriteLine($"{mostRecentFile.Name}");
using (var ms = new MemoryStream())
{
sftpClient.DownloadFile(mostRecentFile.FullName, ms);
var fileContents = Convert.ToBase64String(ms.ToArray());
var mailClient = new SendGridClient(_sendGridApiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("[email protected]", "Example User"),
Subject = "Recent File",
PlainTextContent = "Attached is the most recent file by name.",
};
msg.AddTo(new EmailAddress("[email protected]"));
msg.AddAttachment(mostRecentFile.Name, fileContents);
var response = mailClient.SendEmailAsync(msg).Result;
Console.WriteLine(response.StatusCode);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment