Failure Sending Mail in C# SMTP server - c#

I am writing web services for an application in which there is a registration function and upon registration i have to send an email through the server. i have already done this kind of work for another website with Parallel Plesk server. using the same code i'm trying to send email but getting this exception. I searched Google and some related answers here but all in vain. Help?
"System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'domainname.com'\r\n at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)\r\n at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)\r\n at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)\r\n at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)\r\n at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n --- End of inner exception stack trace ---\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)\r\n at ActivityTracker.Controllers.ValuesController.parentRegistration(parent p) in c:\Users\Harris\Documents\Visual Studio 2012\Projects\ActivityTracker\ActivityTracker\Controllers\ValuesController.cs:line 89"

From the machine running your code:
You CANNOT resolve domainname.com
You CAN resolve to the IP address of domainname.com
This indicates that you are missing an internal DNS entry.
As your machine can talk to the IP but not using the DNS name - you can work around the issue by creating a Hostname entry for the domain name in question.
Here's how to modify your Hostname file:
http://www.rackspace.com/knowledge_center/article/modify-your-hosts-file
Once this entry is in place, you should now be able to ping to domainname.com. When that works - rerun your code.
Some useful DNS reading:
http://www.techrepublic.com/article/understanding-how-dns-works-part-1/
http://social.dnsmadeeasy.com/blog/understanding-dns-forwarding/
NOTE: You've not confirmed if you can telnet to the port in question, so I am presuming this is ok - ruling out any firewall issues.

Try to use GMail SMTP if it works with GMail SMTP then the problem exist with the domain you specified.

Related

DotNetCore SocketException "Cannot assign requested address" SmtpClient

I have an dotnet 5 service that sends emails using the SmtpClient. This service is deployed as a linux docker image running in AWS EKS (Kubernetes).
Running locally on my machine, everything works fine, but when it's deployed to our K8s environment, every SmtpClient.SentAsync call sits for around 10 minutes, before it finally crashes with the following exception:
System.Net.Mail.SmtpException: Failure sending mail.
---> System.Net.Sockets.SocketException (99): Cannot assign requested address
I've researched this error, and there is a lot of talk about using/not using localhost as a host name. In my case, I'm not using local host at all. I'm just trying to send outbound emails using SmtpClient, where the host is a 3rd party SMTP server.
I've tried running this as a linux docker container on my own dev machine, and it also works fine, so it seems to not like something about my EKS environment, yet I can't figure out what that is. Any ideas?
Update:
FYI, the pod can access the internet just fine, using the HttpClient for example. I can also make http calls to it's API on port 80. So it's binding just fine in that regard. It just seems to be an issue when using the SmtpClient.
Stack Track:
System.Net.Mail.SmtpException: Failure sending mail.
---> System.Net.Sockets.SocketException (99): Cannot assign requested address
at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state, Boolean flowContext)
at System.Net.Sockets.Socket.PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
--- End of stack trace from previous location ---
at System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context)
at System.Net.Sockets.Socket.MultipleAddressConnectCallback(IAsyncResult result)
--- End of stack trace from previous location ---
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.TcpClient.EndConnect(IAsyncResult asyncResult)
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.InitializeConnectionCallback(IAsyncResult result)
--- End of stack trace from previous location ---
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result)
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)
...

unable to know what is blocking to my application to communicate to Web service

Recently we were facing an issue in client place is that we were unable to communicate to web service even we checked that there is no system proxy set in that system, to overcome this we had given a dummy proxy (localhost:port) and its started working well but after some days with dummy proxy it was unable to communicate to service if we remove dummy proxy then it started working well. i am not able to understand what is blocking me to communicate to service. what may be the issue and how can we overcome this problem. This issue is happening only on some system.
Actually it has to go and hit this URL http://********-tech.in:8080/******dp/ClientVersion but suddenly it started hitting this one 125.21.244.38:8080 why i am not able to conclude.
2017-05-05 00:19:44,721 ERROR [Heartbeat Service ] - Exception while sending heartbeat to manager.
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 125.21.244.38:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at HeartbeatWSImplService.heartbeat(String probeUid, heartbeatRequest heartbeatRequest)
at ProHance.ProbeHeartBeat.HeartBeat.timer_Elapsed(Object sender, ElapsedEventArgs e)
Please read this post here they are telling to set the default proxy for the webservice request, they are trying to the proxy details while connecting to google. If there is no proxy configured you can try the method mentioned there. Set the default proxy.

SMTP Email Sending

No connection could be made because the target machine actively refused it 127.0.0.1:25
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Net.Sockets.SocketException: No
connection could be made because the
target machine actively refused it
127.0.0.1:25
Source Error:
An unhandled exception was
generated during the execution of the
current web request. Information
regarding the origin and location of
the exception can be identified using
the exception stack trace below.
Stack Trace:
[SocketException (0x274d): No
connection could be made because the
target machine actively refused it
127.0.0.1:25] System.Net.Sockets.Socket.DoConnect(EndPoint
endPointSnapshot, SocketAddress
socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint
remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean
connectFailure, Socket s4, Socket s6,
Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult
asyncResult, Int32 timeout, Exception&
exception) +224
[WebException: Unable to connect to
the remote server]
System.Net.ServicePoint.GetConnection(PooledStream
PooledStream, Object owner, Boolean
async, IPAddress& address, Socket&
abortSocket, Socket& abortSocket6,
Int32 timeout) +5483819
System.Net.PooledStream.Activate(Object
owningObject, Boolean async, Int32
timeout, GeneralAsyncDelegate
asyncCallback) +202
System.Net.PooledStream.Activate(Object
owningObject, GeneralAsyncDelegate
asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object
owningObject, GeneralAsyncDelegate
asyncCallback, Int32 creationTimeout)
+332 System.Net.Mail.SmtpConnection.GetConnection(String
host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String
host, Int32 port) +159
System.Net.Mail.SmtpClient.GetConnection()
+35 System.Net.Mail.SmtpClient.Send(MailMessage
message) +1213
[SmtpException: Failure sending mail.]
System.Net.Mail.SmtpClient.Send(MailMessage
message) +1531
Checkout.btnSend_Click(Object sender,
EventArgs e) +2675
System.Web.UI.WebControls.Button.OnClick(EventArgs
e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +110
I can't send email in live connection but in my local its working.
please help me guys.
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
+13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection
postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3618
here's my C# code..
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "localhost";
//delete session cookie
Response.Cookies["session"].Expires = DateTime.Now.AddYears(-30);
SmtpMail.Send(objEmail);
You forgot to start your SMTP server on that machine
Please don't tell you don't have a SMTP server on that machine. But, if you have to tell that, refer to this page and this page also
Even if you configure the local SMTP server, your emails are most likely to end up in spam folder. Better use the SMTP server of your email provider. If you are using Gmail, have a look at here
I got the error with smtp services installed but not started. To start services on the local machine with smtp already installed, here's the steps I took:
Open Server Manager
Select Local Server
Type "smtp" in the filter box under SERVICES (see image)
Right click on Simple Mail Transfer Protocol Service (SMTP) and
select Start Services

Webservice SocketException - Only Breaks On One Application

I have a few applications which use a single Web Service which resides on the same server as the applications.
Why would only one of the applications have a problem connecting to a web service? And is there a way I can better diagnose exactly what the problem is with the connection?
It won't even connect to a web service the application itself is hosting
I have tried running it from my local machine and it works fine (updated the web ref url and the connection string to point to the liver server), which should rule out that the code itself is the problem.
I have tried setting up a different virtual directory to point to the application; and later copying the entrie app to another location on the same server and setting it up there. No luck.
[SocketException (0x274c): 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 xx.xx.xx.xx:80]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream() +5321194
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
...
Found it... the proxy was the cause of the issue and it is the only application where I specify proxy different from the default:
Since I only need the proxy locally I disabled it on the live web.config with enabled="false"
<defaultProxy enabled="false">
<proxy
autoDetect="False"
bypassonlocal="True"
scriptLocation="http://www.proxy.something"
proxyaddress="http://proxy.com" />
</defaultProxy>

sending mail works on server but not on my local machine

i have the following code below (i have stuck in xxx to not publish the real name). this code works fine when i upload to the server and will send out emails perfectly.
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmailAddress_);
msg.To.Add(new MailAddress(toEmailAddress_));
msg.Subject = subject_;
msg.Body = body_;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("xxx#xxxx.org", "password");
try
{
SmtpClient c = new SmtpClient("mail.xxx.org");
c.UseDefaultCredentials = false;
c.Credentials = basicAuthenticationInfo;
c.Send(msg);
}
catch (Exception ex)
{
throw ex;
Console.Write(ex.Message.ToString());
}
but when i test locally on my machine in visual studio, i get an error:
[SocketException (0x274d): No connection could be made because the target machine actively refused it 66.226.21.251:25]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224
[WebException: Unable to connect to the remote server]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332
System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159
any suggestions of why this wouldn't work
The first thing I'd do to run this down is to see whether the target machine is, as the error message says, actually refusing the connections. I can connect to port 25 on that IP address from here, so it's possible that your error message is misleading. These are all possible causes of a failure to connect:
there's some problem in your code
there's some problem in the library you're using
you have a local firewall preventing outbound mail from strange programs
your ISP does not permit outbound SMTP connections except to their own servers
some intermediate network is blocking things
the mail server's ISP is blocking SMTP connections from your network
the mail server really is rejecting you, perhaps because you're on a blocklist
To get more detail, download and install Wireshark. It's like a debugger for networks. Start a capture between your system and the target network and then run your code. Interpreting the captured packets takes some experience, so if you get stuck feel free to post more data here.
Relay restrictions are most likely preventing you from sending mail from outside an allowed set of IPs. If the SMTP Server is configured on a web/application server, it's probably set up to allow mail to be sent via the 127.0.0.1 only.
You can configure a local SMTP Server via the IIS Manager. If you go down this path, make sure port 25 is opened up on your local machine. Often times anti-virus type software block/monitor this port and it mucks with email delivery.
I think you are not using the port no in your code. Use these lines, Then mail should be gone on local also.
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Timeout = 60000;
smtp.Port = 25;
This is working on my system. I hope it will work also on your local system.
The provider has probably firewalled off their mail server so that it is only accepting mail from their hosting environment.
Change it to use your local mail server when you're testing it locally.
You asked for an XP Mail Server. Try hMailServer
Have a look to see if your antivirus is going crazy, i've have seen this problem a few times with people running mcafee.
Hope this helps.

Categories

Resources