Attach file existing on FTP server to mail in C# .NET - c#

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.

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);

Related

Attaching PDF file in email

I need to attach an receipt in the email which has been generated dynamically. I'm unable to attach the pdf file, it denotes me that path is not valid.
Here is my code:
public static IRestResponse SendConfirmationEmail(string emailaddress,string subject,string body)
{
RestClient client = new RestClient();
client.BaseUrl = "https://123456";
client.Authenticator = new HttpBasicAuthenticator("api", "key-abcdef12345huj");
RestRequest request = new RestRequest();
request.AddParameter("domain", "abc.com", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", "abc <abc#xyz.com>");
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("~/users/Receipts/abc-414.pdf");
request.AddParameter("attachment",attachment);
request.AddParameter("c", emailaddress);
request.AddParameter("to", emailaddress);
request.AddParameter("subject", subject);
request.AddParameter("html", body);
request.Method = Method.POST;
return client.Execute(request);
}
Can any one help me out on this issue?
Thank you
try in this way
attachment = new System.Net.Mail.Attachment(HttpContext.Current.Server.MapPath("~/users/Receipts/abc-414.pdf"));
use Server.MapPath method that returns the physical file path that corresponds to the specified virtual path on the Web server.
I see that you are sending these parameters in a POST request. Did you check the process of serializing-deserializing? maybe there is something wrong in this step and that parameter is ignored

FTP stream request stream issue

The error I am getting is web exception. The requested URI is invalid for this FTP command.
I am unsure as how to fix it. Anyone got any idea's? Thanks
private void SendFile(FileInfo file)
{
Console.WriteLine("ftp://" + ipAddressTextField.Text);
// Get the object used to communicate with the server.
string ftp = "ftp://" + ipAddressTextField.Text;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(usernameTextField.Text, passwordTextField.Text);
// Copy the contents of the file to the request stream.
byte[] fileContents = File.ReadAllBytes(file.FullName);
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
Seems you're not setting a destination filename for the upload so the server has no file name to use for the uploaded file.
You could just set it the same as the source file name using something like;
string ftp = "ftp://" + ipAddressTextField.Text + "/" + file.Name;
Console.WriteLine(ftp);
To do a slightly more robust creation of the Uri in case that the file names may have special characters, you could use the Uri class to build it, and pass that in to WebRequest.Create instead.

Can a curl command passing in a username and password credentials in the URL work in a C# program/.net environment

Can a curl command passing in a username and password credentials in the URL work in a C# program/.net environment?
Example:
curl -T testfile.txt 'http://user:password#domain.net/dir/
What would be the equivalent of the Curl command in a C# .net environment?
My original problem started by trying to uplaod a file to a webdav server. I tried using C# webclient and httpwebrequest...... and keep getting 401 autnetication errors even though the credentials was in the actual header of the request.
When I use Curl in a unix environment I had no problems uploading the file.
I am not sure if the problem is with the redirect that HttpWebrequest does:
webclient how to keep basic authorization when redirect
Thats is:
401 - authentication error - No username and password in header
Then - 301 redirect - This includes username and password in header
just try the below code... it will help you...
string fileToUpload = #"c:\testfile.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/Upload");
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential ("username", "password");
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);
byte[] inData = new byte[rdr.Length];
// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();
req.GetResponse();
// after uploading close stream
reqStream.Close();

using ftpWebRequest with an error: the remote server returned error 530 not logged in

I am trying to use the ftpWebRequest in c#
my code is
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.20.10/file.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("dev\ftp", "devftp");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"\file.txt");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
request.UsePassive = true;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
and I get an Error in request.GetRequestStream();
the error is: the remote server returned error 530 not logged in
if I try to go in to a browser page and in the url I write ftp://192.168.20.10/
the brows page is asking me for a name and password, I put the same name and password and I see all the files and folders in the ftp folder.
Shouldn't the line:
request.Credentials = new NetworkCredential("dev\ftp", "devftp");
be:
request.Credentials = new NetworkCredential("dev\\ftp", "devftp");
or:
request.Credentials = new NetworkCredential(#"dev\ftp", "devftp");
I have to believe this may be causing your issues because the \f is a form feed character.
Faced the same issue, here's my solution:
request.Credentials = new NetworkCredential(
usernameVariable.Normalize(),passwordVariable.Normalize(),domainVariable.Normalize());
Details can be found here
Hope it helps.
I found out that when connecting via .NET/C# to a FTP-server some characters are not "valid". After setting the login credentials to only contain letters and numbers [a-Z0-9] it worked to log in.
Just remove the double quote from username or password because sometimes $ sign in username or password causes problem. Its good to use single quote every time.
If you assume anonymous logon do not set network credentials. this was the root of my problems.

Help needed on Uploading Files in windows mobile

I have an desktop application running on my desktop.
I need to send the file path to the CGI script running at server.
CGI script taks the file path and upload the contents from my machine.
I tried to send the file path through httppost method; it is not working - can any one suggest me how to do.. methods I have tried are:
WebClient upload = new WebClient();
NetworkCredential nc = new NetworkCredential("test", "admin");
Uri URL = new Uri("http:\\10.10.21.55\\cgi-bin\\file_upload.cgi");
upload.Credentials = nc;
byte [] data = upload.UploadFile(filepath, "c:/Data.txt");
Console.WriteLine(data.ToString());
and the other way I tried is:
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://10.10.21.55/cgi-bin/file_upload.cgi");
WebResponse rsp = null;
request.Method = "POST";
request.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.WriteLine("hi hiw are you");
writer.Close();
both ways are not working.
but the below answered code works in desktop in winmo its telling WebClient not implimented...
please tell how to send data to script present in server in windows mobile
Is this as simple as getting the WebClient parameters right? (you seem to be passing in file-path as the url, and not using the encoding):
using(WebClient upload = new WebClient()) {
NetworkCredential nc = new NetworkCredential("test", "admin");
upload.Credentials = nc;
byte[] data = upload.UploadFile(
#"http://10.10.21.55/cgi-bin/file_upload.cgi", #"c:\Data.txt");
Console.WriteLine(upload.Encoding.GetString(data));
}

Categories