How does System.Net.Mail.SMTPClient do its local IP binding - c#

We have a load balanced (NLB) ASP.NET web app which sends email.
The servers are dual homed with an external facing and internal (behind firewall) facing IP. The Mail server is behind the firewall.
We have been seing a problem where the SMTPClient class throws an exception stating it is unable to connect to the SMTP server.
The networking guys are telling us they are seeing attempts to connect to the SMTP server from the external facing IP address (which the firewall is blocking)
From my (admittedly patchy) knowledge of network enabled applications I thought that the local IP binding would be decided based on the destination, i.e. if the routing tables say the IP address can be accessed through a particular NIC than that is the IP the outbound request is generated from. Am I wrong?
looking at SmtpClient.ServicePoint I'm beginning to think that we might be and that we can (should) force an explicit binding to a particular IP?
specifically I've been looking at
ServicePoint.BindIPEndPointDelegate Property
from that page...
Remarks :Some load balancing techniques
require a client to use a specific
local IP address and port number,
rather than IPAddress.Any (or
IPAddress.IPv6Any for Internet
Protocol Version 6) and an ephemeral
port. Your BindIPEndPointDelegate can
satisfy this requirement.
it just seems a little odd to me that I'd need to do that but perhaps thats common in this type of environment?

You need to do something like this...
public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount);
private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) {
if (retryCount < 3 && ddSendFrom.SelectedValue.Length > 0)
return new IPEndPoint(IPAddress.Parse("192.168.1.100"), 0); //bind to a specific ip address on your server
else
return new IPEndPoint(IPAddress.Any, 0);
}
protected void btnTestMail_Click(object sender, EventArgs e) {
MailMessage msg = new MailMessage();
msg.Body = "Email is working!";
msg.From = new MailAddress("me#me.com");
msg.IsBodyHtml = false;
msg.Subject = "Mail Test";
msg.To.Add(new MailAddress("you#you.com"));
SmtpClient client = new SmtpClient();
client.Host = "192.168.1.1";
client.Port = 25;
client.EnableSsl = false;
client.ServicePoint.BindIPEndPointDelegate = new System.Net.BindIPEndPoint(BindIPEndPointCallback);
client.Send(msg);
}

Related

`The operation has timed out.` exception when sending mail using ZOHO SMTP configuration

I am using ZOHO mail server for sending mails through my application. But its unable to connect to server and throws exception The operation has timed out.. Following is my code:
public int sendMail(string from, string to, string subject, string messageBody) {
try {
SmtpClient client = new SmtpClient();
client.Port = 465;
client.Host = "smtp.zoho.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(Username, Password);
MailMessage mm = new MailMessage(from, to, subject, messageBody);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.IsBodyHtml = true;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
return 0;
} catch (Exception) {
throw;
}
}
I also tried using port 587 as suggested here Send email using smtp but operation timed out using ZOHO. But still problem persists.
Zoho SMTP Configuration help link: https://www.zoho.com/mail/help/zoho-smtp.html
Time out problems are usually related to network, ports problems, I haven't experience sending emails using SSL or TLS methods but I'd check this too, of course I suppouse you changed the port number when you say you tried TLS.
After trying all kinds of firewall/anti-virus/router port forwarding, port scanners, website port checkers I simply found out that with code almost identical to yours I was able to send mail successfully!
All you need to do is change smtp to:
smtp.zoho.eu
and port to:
587

Closing Transmission Error. Timeout waiting for the data from client

I am using local host to send bulk mails through SES. This question is answered by many but none of the solutions is helping me. The problem is I could send 100/ 150 mails at a time after that the above error is showing up. I tried to dispose of the client as suggested by some, but not working. I am using C# code to do this. Any answers/ suggestions is much appreciated. The below is the code I am using to send bulk mail using for loop. You might be thinking it might be a throttling issue, it is not because we have 70 emails/second and 500000 emails per day.
Parallel.For(0, mail.Count, i =>
{
// Replace with your "From" address. This address must be verified.
String TO = mail; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
// Create an SMTP client with the specified host name and port.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
//Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
//the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.Send(message1);
client.Dispose();
}
});
I don't know the exact reason why it is working now, but it's working. I changed the logic of the above code, it started working. Instead of fetching the SMTP connection each time, for sending each mail previously, this time I fetched the smtp connection only once and used it to send all the bulk mails at once and it started working.But the problem is the sending time, it is taking too much to send all the mails.Anyways I will find the solution for this also.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
client.EnableSsl = true;
for(i=0;i<mail.Count;i++)
{
String TO = mail[i];
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message1);
}
client.Dispose();
}
Label1.Text = mail.Count.ToString() + " mails sent !!";

Only getting "no connection could be made because the target machine actively refused it" on certain computers

The program runs on multiple computers within the same network. The mail is sent through an internal server. When I try to send an email from SmtpClient, it works on some computers but on others it gives me:
"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 10.1.0.74:25"
I've tried looking it up and a lot of answers talk about the firewall or the smtp server blocking requests. The problem is it only errors on certain computers, and I'm unsure what the firewall settings are supposed to be.
The code for sending the email is as follows:
public void SendMessage(string subject, string messageBody, string fromAddress, string toAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient("10.1.0.74", 25);
// Set the sender's address
message.From = new MailAddress(fromAddress);
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
if (addr.Trim() != "")
message.To.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
message.IsBodyHtml = true;
// Set the SMTP server to be used to send the message
//client.Host = "smtp.gmail.com";
System.Net.NetworkCredential a = new System.Net.NetworkCredential("User", "Pass");
//client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = a;
// Send the e-mail message
client.Send(message);
}
Edit:
Pinged the IP from the computer that's not working, got the following.
Enable SSL in your client and try other ports:
client.EnableSsl = true;
client.Port = 587;
// or
client.Port = 465;
Also you can check the connection with cmd command:
telnet smtp.gmail.com 587
Successful response usually looks like:
220 mx.google.com ESMTP

Can i use IP Address as SMTP host rather then smtp.email.com

i am creating an Email sending sample application, and i want to use send email from different email address like "gmail, yahoo, hotmail" so i don't want to use "smtp.email.com" as host, because if i use "smtp.email.com" as host i will have to change my host name for every different company like("smtp.gmail.com" for gmail or "smtp.mail.yahoo.com" for yahoo.com ) so
Can i use IP Address as SMTP host rather then smtp.email.com.
Please give me a solution for this so that without changing smtp host name i can use different email company to send email.
this is my code:
try
{
// setup mail message
MailMessage message = new MailMessage();
message.From = new MailAddress(textBox1.Text);
message.To.Add(new MailAddress(textBox2.Text));
message.Subject = textBox3.Text;
message.Body = richTextBox1.Text;
// setup mail client
SmtpClient mailClient = new SmtpClient("smtp.gmail.com");//here i have to change SMTP host for different email company
mailClient.Credentials = new NetworkCredential(textBox1.Text,"password");
// send message
mailClient.Send(message);
MessageBox.Show("Sent");
}
catch(Exception)
{
MessageBox.Show("Error");
}
Sure you could use IP addresses instead of names, but remember then if they ever changed the IP you're goning to stop working.. BUT.... this needs to change depending on what you are sending the mail as unless you find some form of relay proxy thats open.. AS yahoo wont recveive gmail and gmail wont receive yahoo etc.. The reality is if you are sending as that it would end up changing wether you used an IP or a name.
Your webserver however will most likely send mails from your domain, rather than your gmail/yahoo accounts.. why not send it from your domain? eg noreply#myweb.com then the smtp server remains the same as its your web provider
Of course you could do
SmtpClient mailClient
if (textbox1.Text.Contains("gmail")
{
mailClient = new SmtpClient("smtp.gmail.com");/
mailClient.Credentials = new NetworkCredential(textBox1.Text,"password");
}
else if (textbox1.Text.Contains("somemail")
{
mailClient = new SmtpClient("smtp.somemail.com");/
mailClient.Credentials = new NetworkCredential(textBox1.Text,"password");
}
etc

Send mail works locally but not on server?

This code works locally, but when I upload it to my server on Godaddy, it does not send the e-mail. Any idea why it doesn't work on their server? What do I need to change?
try {
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("Myemail#gmail.com");
mail.To.Add("Myemail#gmail.com");
mail.Subject = "New sign up";
mail.Body = "New member";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("Myemail#gmail.com", "**Mypass**");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
} catch(Exception ex) {
throw ex;
}
They may be blocking outgoing SMTP connections in order to prevent spammers from using their service to send spam. You should check what error messages you're getting and check your server host's policy.
There are a couple of things you need to do when sending from inside a site hosted from Godaddy. Use their relay server to send the message (this won't work from your dev machine, you'll have to test it live after you upload it). Here is the relay server info. Also make sure the "from" address is an email within the same domain. I usually use the same as the toAddress. See here for info on why this is necessary.
This is the code I'm using to send from a site inside Godaddy:
btnSend.Disabled = true;
const string serverHost = "relay-hosting.secureserver.net";
var msg = new MailMessage(toAddress, toAddress);
msg.ReplyTo = new MailAddress(emailFrom);
msg.Subject = subject;
msg.Body = emailBody;
msg.IsBodyHtml = false;
try
{
var smtp = new SmtpClient();
smtp.Host = serverHost;
smtp.Credentials = new System.Net.NetworkCredential("account", "password");
smtp.Send(msg);
}
catch (Exception e)
{
//Log the errors so that we can see them somewhere
}
You need to send your email via the godaddy smtp servers. I experienced the same issue with them before I think. I believe they give instructions of how to login via their FAQ.
If you have ssh access to the server, try to telnet smtp.google.com via 25 and 465 ports also. If you get a timeout, then you're likely firewalled from connecting to these ports outside a certain IP range.
Port 587 is for TLS. As you're using SSL, try port 465.

Categories

Resources