3

I am trying to attach a file saved on an FTP Server to a SMTP mail message.

mail.Body = body;

System.Net.Mail.Attachment attachment;

attachment = new System.Net.Mail.Attachment(Server.MapPath("Documents/quote.pdf"));
mail.Attachments.Add(attachment);
SmtpServer.Send(mail);

However, finding the attachment seems to trouble, due to an authentication issue. I am not quite sure if I should use a RequestStream and get the response, or if there is a way to authenticate the path for reading and adding the attachment to the email. The issue with the RequestStream is that I cant get the filename, which is what I need to add as a parameter when creating an attachment. Any advise? Thanks in advance.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Zayd Chopdat
  • 77
  • 1
  • 8
  • What `RequestStream` are you referring to? What do you mean by *"cant get the filename"*? If you want to retrieve a file from FTP, you have to know it's name. After all, the name is in your code! – Martin Prikryl May 28 '18 at 06:22

1 Answers1

2

Use FtpWebRequest to obtain a Stream referring to a file contents on an FTP server. And then use an overload of Attachment constructor that takes a Stream.

const string filename = "quote.pdf";

var url = "ftp://ftp.example.com/remote/path/" + filename;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

Stream contentStream = request.GetResponse().GetResponseStream();
Attachment attachment = new System.Net.Mail.Attachment(contentStream, filename);
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992