Using SmtpClient, and getting "the target machine actively refused it" - c#

I am trying to use System.Net.Mail for an application to send an email, but get this exception:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: No connection could be made
because the target machine actively refused it 198.238.39.170:25
The code I am using is:
string mailserver = "Scanmail.ofm.wa.lcl";
MailMessage msg = new MailMessage("albert#einstein.net", "snark#snarky.com", "Very subjective", "A message body!");
SmtpClient client = new SmtpClient(mailserver);
client.Send(msg);
Obviously the email addresses above are fictional, but in the actual code it uses real email addresses in the system. The mail server address is accurate.
I am tempted to think that I need to put some kind of security credentials in there, but not sure where - although #Andre_Calil's advice suggests this is not the problem, and that possibly the mail server is configured to prevent my development machine from connecting. So how is this to be overcome?

So, as we were talking, your server is probably configured to deny relay from every machine, which is a recommended security setting.
From your development machine, open a prompt (command) and type telnet SMTP_SERVER_IP_ADDRESS 25. This command will try to stablish a basic socket connection on port 25, which is the default SMTP port. If it's successful, you'll still have to discover whether the server requires authentication.
However, if it's unsuccesful, you'll have to put your code on hold until you can get the help of a sysadmin.
One other thing to try is to repeat this same test from a app server, because the SMTP server may be configured to allow app_server and deny everybody_else.
Regards

Related

WinSCP .NET library FTP transfer fails with "IP addresses of control and data connection do not match"

I have implemented FTP code with use of WinSCP .NET assembly and hosted it on an Azure AppService.
It works locally and on Azure.
But in very few random times, when hosted on Azure, it throws the following error:
Error transferring file 'D:\local\Temp\test_settings.txt'. Server sent passive reply with unroutable address 10.YYY.YYY.YYY, using host address instead. Copying files to remote side failed. Rejected data connection for transfer of "/test_settings.txt", IP addresses of control and data connection do not match
Since the IP starts with 10. does that mean that it's local in the FTP server's network?
Can I do something to improve the implementation?
Do you think that the solution will have a problem when used concurrently by multiple requests?
My code is a copy of the Simple C# example with the following settings:
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
UserName = username,
Password = password,
GiveUpSecurityAndAcceptAnyTlsHostCertificate = true,
FtpSecure = FtpSecure.Explicit,
HostName = 'ftp.domain.com'
};
IP addresses of control and data connection do not match
That's a message from FileZilla FTP server. It's a security measure. It might indicate that external IP address of your app service instance changed mid transfer. Or of course, it might indicate that you connection was hijacked (that's what the server tries to detect).
It has nothing to do with WinSCP.
I do not know if the IP address of the Azure app service can be fixed somehow. If not, all you can do is to reconnect and retry the transfer. I believe you would have the same problem with any FTP client. Maybe with IPv6 connection, the problem would not happen. But I'm not sure, it's just a wild guess. Though you cannot force IPv6 with WinSCP (only by disabling IPv4 altogether, but I do not know if that's even possible with the app service).

How to send an email from office365 account using domain windows authentication

I'm developing a console app which will be executed from a windows service that needs to send emails using the domain account associated to the domain account running the windows service.
In my development machine I'm logged with a domain account that belongs to the same domain that will run the windows service but I'm not able to get it working properly.
For this development I'm using .NET 4.6.1 and the nuget package FluentEmail.Smtp
My code looks like this:
Email.DefaultSender = new SmtpSender(new SmtpClient
{
UseDefaultCredentials = true,
EnableSsl = true,
Host = "smtp.office365.com",
TargetName = "STARTTLS/smtp.office365.com",
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network
});
await Email.From("myname#mycompanydomain.com", "Some tittle")
.To(emailListObject)
.Subject("Some subject")
.Body("Some body", true)
.SendAsync();
With this code I'm getting the following exception:
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 52.96.9.178:587
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result)
at System.Net.Mail.SmtpTransport.EndGetConnection(IAsyncResult result)
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)
Note: From my machine I'm able to ping the IP mentioned in the exception
I'll appreciate your assistance
For starters you might want to take a look at the official document - direct send. You will note that there are quite a few issues (such as TLS security) alongside proper configuration of your Exchange server.
Without more information in your question it is rather limited as to what can be answered, however as an alternate solution, maybe take a look at direct send. (which is much less effort).
Settings for direct send
Enter the following settings on the device or in the application directly.
Server/smart host. Use your MX endpoint, for example, contoso-com.mail.protection.outlook.com
Port. Use port 25
TLS/StartTLS. Enable this.
Email address. Use any email address for one of your Office 365 accepted domains. This email address does not need to have a mailbox.
Microsoft recommends adding an SPF record to avoid having messages flagged as spam. If you are sending from a static IP address, add it to your SPF record in your domain registrar's DNS settings as follows:
DNS entry Value
SPF v=spf1 ip4:<Static IP Address> include:spf.protection.outlook.com ~all

Renci ssh.net No connection could be made because the target machine actively refused it

We recently deployed a project into production and are now receiving this error message when we attempt to connect to the external sftp machine, "No connection could be made because the target machine actively refused it". When I was developing the application and testing it, we had no issues connecting to this server.
What would be different? I have administrative privileges and the app pool on the production server does not. I'm not sure if this could be what's causing the issue or if it may be something on the external client's server or their firewall blocking us.
If you are using localhost, specify 127.0.0.1 instead.
When I was using SSH.Net and the host was specified as localhost it threw the exception that the host actively refused the connection WSAECONNREFUSED - 10061. When I specified 127.0.0.1 instead, the connection could be made.
I think this is due to the implementation in SSH.Net:
internal static IPAddress GetIPAddress(this string host)
{
IPAddress ipAddress;
if (!IPAddress.TryParse(host, out ipAddress))
ipAddress = Dns.GetHostAddresses(host).First();
return ipAddress;
}
Which does not resolve a valid hostname for localhost, apparently. C# Interactive yields the following:
> Console.WriteLine(Dns.GetHostAddresses("localhost").First());
::1
The value ::1 does not seem to be a valid IP address for sockets to use.
This is a standard TCP error
WSAECONNREFUSED - 10061
From the Client's point of view it means 'there is no socket at that address listening to that port' (the "actively refused" is a red herring).
i) check the address
ii) check the port
iii) check firewall(s)
From our extensive experience (we offer own networking components) -- it's a firewall problem. The firewall doesn't let your requests pass. It's a common situation when you run say Putty, and it works, but your code doesn't. This is because many firewalls detect well-known applications and let them pass, while preventing other applications.

C# Winforms Application Failure in sending Email: The remote name could not be resolved: 'smtp.gmail.com ; Operation Timed out

My WinForms C# program sends email. I've used MailMessage and SmtpClient.
In the constructor of SmtpClient I passed smtp.gmail.com and port 587.
This is working on my friend's computer, however when I try it I get this error:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'smtp.gmail.com'
System.Net.Mail.SmtpException: Operation Timed out
How do I fix this error? Why is it specific to my computer?
If i use port 25 i get exception : Operation Timed out
If i use port 587 i get exception : The remote name could not be resolved: 'smtp.gmail.com'
if i use port 465 i get exception : Operation Timed out
Try some basic network troubleshooting. First, ensure you can ping something by IP address, this does not need DNS to work, so try ping 173.194.41.86 and see if you get some replies.
Then ping www.gmail.com from your machine with ping www.gmail.com. This should tell you if your network can resolve any names to IP addresses. You should get four IP address pings in the response the same as above.
If it does not, then your DNS configuration is bad. If you have a static IP address then you will need to check with a network admin or set the DNS servers the same as the working machine. If its dynamic then you might try ipconfig /renew to get the latest settings from the DHCP server.
If pinging www.gmail.com worked then try ping smtp.gmail.com to see if the smtp host is resolving. If it does not, then there's still a DNS issue but one that is effecting only the smtp hostname.
Try ipconfig /flushdns to clear the local DNS cache and try again. Try rebooting, if not on a prod server.
You can also use nslookup to check DNS name resolution and also Resolve-DnsName in PowerShell, possibly only in 3.0 though.
Also, check any firewall settings.
Mark EnableSsl in your SmtpClient to true.
smtpClient.EnableSsl = true;

Unable to send mail from ASP.NET web page

I have a Contact Us page in my website from which I am trying to send mail.Here is my code
MailMessage feedBack = new MailMessage();
feedBack.To.Add("some#some.com");
feedBack.From = new MailAddress("MyClient#some.com");
feedBack.Subject = "Mail from My Client's Website.";
feedBack.Body = "Sender Name: " + Name.Text + "<br/><br/>Sender Last Name:"+LastName.Text+"<br/><br/>Sender Company:"+Company.Text+"<br/><br/>Sender Designation:"+Designation.Text+"<br/><br/>Sender Email:"+Email.Text+"<br/><br/>Sender Phone No:"+ PhoneNo.Text+"<br/><br/>Sender Enquiry:"+Enquiry.Text;
feedBack.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.MyClient.com"; //Or Your SMTP Server Address
//smtp.Port = 25;
//smtp.EnableSsl =false;
smtp.Credentials = new System.Net.NetworkCredential("MyClient#some.com","XXXX");
//Or your Smtp Email ID and Password
smtp.Send(feedBack);
All the time I keep getting this error
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 64.37.118.141:25
I have verified with my client and all the details are correct(smtp server name,credentials).
I also tried setting port to 587 and 465 but it did not work.
Can someone help me out with this?
What can be the cause?
I am not able to find it.
Any suggestions are welcome.
I tested the ip above with port 25 through telnet and got the following response:
Command:
telnet 64.37.118.141 25
Response:
Could not open connection to the host, on port 25: Connect failed
Most likely port 25 is being blocked. You will need to find what port is used with your pop/smtp servers.
MEDIUM TRUST
If you are on a shared hosting service, chances are that ASP.Net is set to run in medium-trust (as it should). This restricts SMTP to port 25 only, you cannot use any other port.
SMTP problems when ASP.NET is not running in full-trust
SO similar post
Have you checked that the server that the web application resides on is set up to be allowed to send mail through the SMTP server? Trust connections sometimes have to be setup to allow relaying off one server throught another.

Categories