Unable to connect to FTP Server with SOCKS5 using WinSCP - c#

I choose WinSCP so I can implement a SOCKS5 Proxy into my FTP Client.
With the Proxy commented out I am able to connect and download files from a FTP Server without a proxy.
If I try to connect to the FTP Server with SOCKS5 Proxy I am unable to connect.
Any erros in my proxy configuration or something ? LoginData is correct, works with filezilla.
public void Download(string LocalFile)
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = LoginData.Servername,
UserName = LoginData.Username,
Password = LoginData.Passwort,
};
// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "2"); // socks5 proxy
sessionOptions.AddRawSettings("ProxyHost", "***"); //host ip
sessionOptions.AddRawSettings("ProxyPort", "***"); //Port
sessionOptions.AddRawSettings("ProxyUsername", "***"); //Username
sessionOptions.AddRawSettings("ProxyPassword", "***"); //Password
using (Session session = new Session())
{
session.DisableVersionCheck = true;
// Connect
session.Open(sessionOptions);
// Download files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult =
session.GetFiles(LoginData.RemoteFile, LocalFile, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
}
}

With FileZilla, your proxy host is socks.cgm.ag - CGM
With WinSCP, your proxy host is socks.cmg.ag - CMG

Related

Use URL instead of hostname with WinSCP .NET assembly

I am using WinSCP to upload a file to an FTP host. But I only had ftp://xxx.xx.xx.xx path, not hostname like ftp.example.com.
Can I use ftp://xxx.xx.xx.xx for hostname?
My code is based on
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3");
sessionOptions.AddRawSettings("ProxyHost", "proxy");
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload file
string localFilePath = #"C:\path\file.txt";
string pathUpload = "/file.txt";
session.PutFiles(localFilePath, pathUpload).Check();
}
The ftp://xxx.xx.xx.xx URL specify that you want to connect with FTP protocol to xxx.xx.xx.xx host.
That's what you do in WinSCP .NET assembly by setting SessionOptions.Protocol and SessionOptions.HostName:
var sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "xxx.xx.xx.xx",
...
};
Or you can use SessionOptions.ParseUrl:
var sessionOptions = new SessionOptions();
sessionOptions.ParseUrl("ftp://xxx.xx.xx.xx");
...

C# SmtpException - problem with sending mails

Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...
When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s
Here's the code:
protected void SendMessage(object sender, EventArgs e)
{
// receiver address
string to = "******#student.uj.edu.pl";
// mail (sender) address
string from = "******#gmail.com";
// SMTP server address
string server = "smtp.gmail.com";
// mail password
string password = "************";
MailMessage message = new MailMessage(from, to);
// message title
message.Subject = TextBox1.Text;
// message body
message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;
SmtpClient client = new SmtpClient(server, 587);
client.Credentials = new System.Net.NetworkCredential(from, password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
try
{
client.Send(message);
// ui confirmation
TextBox3.Text = "Wysłano wiadmość!";
// disable button
Button1.Enabled = false;
}
catch (Exception ex)
{
// error message
TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
}
}
I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?
Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.
Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.
void Main()
{
UserCredential credential;
using (var stream =
new FileStream(#"C:\credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels = request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
//Console.Read();
var msg = new Google.Apis.Gmail.v1.Data.Message();
MimeMessage message = new MimeMessage();
message.To.Add(new MailboxAddress("", "toemail.com"));
message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere#gmail.com"));
message.Subject = "Test email with Mime Message";
message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
var ms = new MemoryStream();
message.WriteTo(ms);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string rawString = sr.ReadToEnd();
byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
msg.Raw = System.Convert.ToBase64String(raw);
var res = service.Users.Messages.Send(msg, "me").Execute();
res.Dump();
}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";
Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.
Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.

How do I rename file before sending

I am using Mailkit with c# to send an email with an attachment.
How do I rename the attachment before sending the email?
I am currently using the code below but throws an error when deployed in IIS.
var username = "username";
var password = "password";
var displayname = "display";
var from = new MailboxAddress(displayname, username);
var to = new MailboxAddress("User", emailto);
msg.From.Add(from);
msg.To.Add(to);
msg.Subject = emailsubject;
var attachment = new MimePart("application","zip")
{
Content = new MimeContent(File.OpenRead(Path.Combine(fileutil.GetDir, "originalname.zip"))),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = "new filename.zip"
};
var msgbody = new BodyBuilder
{
HtmlBody = string.Format(#"Message"),
TextBody = "Test Message!"
};
msgbody.Attachments.Add(attachment);
msg.Body = msgbody.ToMessageBody();
var client = new SmtpClient();
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(msg);
client.Disconnect(true);
client.Dispose();
Edit: After a bit of digging, I found out that this is the exception thrown
The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.
• An intermediate certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.```
Try this:
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (o, c, ch, e) => true;
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);

Client Email - C#

I can't understand why this code is not working.
I have this error:
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.Read ()
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.SendCore
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.SendInternal
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.Send
static void Main(string[] args)
{
var smtp = new SmtpClient
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true,
Host = "smtp.gmail.com",
//465 SSL se uso 25 solo ad utenti google mando
Port = 465,
Credentials = new NetworkCredential("id", "password"),
};
Console.WriteLine("Mail From: ");
var fromAddress = new MailAddress(Console.ReadLine());
Console.WriteLine("Mail To: ");
var toAddress = new MailAddress(Console.ReadLine());
Console.WriteLine("Subject: ");
string subject = Console.ReadLine();
Console.WriteLine("Body: ");
string body = Console.ReadLine();
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
try
{
smtp.Send(message);
}
catch(Exception ex)
{
Console.WriteLine("Unable to send message due to the following reason: " + ex.ToString());
}
}
how can I solve these problems?
Try port 587 instead of 465. Port 465 is technically deprecated.
from the OP's comment:
Even if I set the port on 587 I have the same errors. In addition, Gmail tells me that someone attempted to access my account
If that's the case when you are using port 587 then you should allow less secure applications in your gmail settings. If you are using 2 factor authentication then you also need to add an application password and use that instead.

Secure Server is not receiving what I am sending

I am trying to connect to server via TLS 1 on Windows.
here is how I am connecting to server
public void Connect(string hostName, int port)
{
this.tcpClient.Client.Connect(hostName, port);
RemoteCertificateValidationCallback validationCallback = new RemoteCertificateValidationCallback(ServerValidationCallback);
LocalCertificateSelectionCallback selectionCallback = new LocalCertificateSelectionCallback(ClientCertificateSelectionCallback);
EncryptionPolicy encryptionPolicy = EncryptionPolicy.RequireEncryption;
this.sslStream = new SslStream(this.tcpClient.GetStream(), true, validationCallback, selectionCallback, encryptionPolicy);
//handshake
X509CertificateCollection clientCertificates = GetCertificates();
this.sslStream.AuthenticateAsClient(hostName);
//this.sslStream.AuthenticateAsClient(hostName, clientCertificates, SslProtocols.Tls, true);
}
Than I am sending messages via method
this.sslStream.Write(messageBytes);
this.sslStream.Flush();
this.tcpClient.GetStream().Flush();
Server did not receiving anything from me.

Categories

Resources