Two Asp.Net Applications sending email through SMTP from same server - c#

I have an Asp.Net application running from AWS, and it has some process that require it to send e-mails automatically (the usual welcome, confirm email, etc...).
I was able to configure it and publish it. It works fine. But as the website enters "Production", I need to run a second application for testing purposes. I'm able to create it, and differentiate which one is being requested by the bindings in IIS.
The issue when both are up and running is that when I try to send an e-mail from the "Production" one, it works fine. But from the "Test" one, I get the following Exception:
[0:] {"$id":"1","Message":"Bad Request:System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: 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 177.185.201.253:587\r
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)\r
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)\r
--- End of inner exception stack trace ---\r
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result)\r
at System.Net.Mail.SmtpTransport.EndGetConnection(IAsyncResult result)\r
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)\r
--- End of inner exception stack trace ---\r
at Shappa.BackEnd.Helpers.EmailSender.<NewPhotoRequired>d__2.MoveNext() in C:\\Andre\\Shappa\\Shappa.BackEnd-Dev\\Shappa.BackEnd\\Helpers\\EmailSender.cs:line 112\r
--- End of stack trace from previous location where exception was thrown ---\r
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r
at Shappa.BackEnd.Controllers.AdminController.<PostPhotoReproved>d__2.MoveNext() in C:\\Andre\\Shappa\\Shappa.BackEnd-Dev\\Shappa.BackEnd\\Controllers\\AdminController.cs:line 78"}
My Code to send email is pretty simple:
public async Task<bool> SendEmail(MailMessage message)
{
try
{
using (var smtp = new SmtpClient())
{
var credential = Config.SMTPCredential;
smtp.Credentials = credential;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.Host = "smtp.gmail.com";
//smtp.EnableSsl = true;
#if DEBUG
smtp.Host = "smtp.kinghost.net";
#else
smtp.Host = "smtpi.kinghost.net";
#endif
smtp.EnableSsl = true;
smtp.Port = 587;
await smtp.SendMailAsync(message).ConfigureAwait(false);
}
}
catch (Exception ex)
{
throw ex;
}
return true;
}
Any ideas?

I found it. Thanks dlatikay for your comment. It helped me find my stupid mistake.
177.185.201.253:587 this is an IP in Brazil, which meant I was deploying the application in DEBUG mode. Checking the options for publish, I was able to change it to Release. Now it works perfectly from both applications.

Related

Connecting to a device on the local network over TCP *sometimes* fails with "No Route To Host" socket error

I'm making an Android app (using Unity and C#) which needs to connect over TCP to a different app running on another device (using the .NET System.Net.Sockets.TcpClient and TcpListener classes). The way this works is the host app broadcasts a UDP packet giving info on its local IP (192.168.x.x) and its TCP listening port. Upon receiving the UDP packet, the Android app attempts to connect to the TCP endpoint given. Most of the time (~80%), this works perfectly and the two devices establish a valid TCP connection. Sometimes though, the Android app receives the UDP packet, tries to connect over TCP but a "No Route To Host" socket error shows up instead; even trying again upon receiving the next UDP packet fails.
I'm suspecting that this is to do with the router creating different subnets. I'm not very familiar with networking code, so I'm not sure how to forward the TCP request over to a different subnet of the local network. What's weird is that the UDP packet is always received no matter what; and most of the time, the TCP request will fail for 10 minutes straight then start working again like nothing happened.
public async Task<bool> ConnectToHost(IPEndPoint endpoint) {
try {
TcpClient client = new TcpClient();
client.NoDelay = true;
IPAddress ipv4 = endpoint.Address;
Debug.Log("IPv4: " + ipv4);
await client.ConnectAsync(ipv4, endpoint.Port); // <--- this call throws the SocketException
Debug.Log("Connected.");
// ...
return true;
}catch(SocketException se) {
Debug.LogError("[TCPClient] Socket Exception (" + se.ErrorCode + "), cannot connect to host: " + se.ToString(), this);
}catch(Exception e) {
Debug.LogError("[TCPClient] Error, cannot connect to host: " + e.ToString(), this);
}
return false;//Could not connect
}
The ConnectAsync() call fails on the client side, giving the following SocketException (error code 10065, WSAEHOSTUNREACH); on server side, no trace of the message is ever seen.
05-29 13:31:54.591: I/Unity(24587): IPv4: 192.168.1.21
05-29 13:31:54.591: I/Unity(24587):
05-29 13:31:54.591: I/Unity(24587): (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 48)
05-29 13:31:58.103: E/Unity(24587): [TCPClient] Socket Exception (10065), cannot connect to host: System.Net.Sockets.SocketException (0x80004005): No route to host
05-29 13:31:58.103: E/Unity(24587): at System.Net.Sockets.SocketAsyncResult.CheckIfThrowDelayedException () [0x00014] in <9eab73f5583e4ab3921ff80e74ccdb29>:0
05-29 13:31:58.103: E/Unity(24587): at System.Net.Sockets.Socket.EndConnect (System.IAsyncResult asyncResult) [0x0002c] in <9eab73f5583e4ab3921ff80e74ccdb29>:0
05-29 13:31:58.103: E/Unity(24587): at System.Net.Sockets.TcpClient.EndConnect (System.IAsyncResult asyncResult) [0x0000c] in <9eab73f5583e4ab3921ff80e74ccdb29>:0
05-29 13:31:58.103: E/Unity(24587): at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x00019] in <a6266edc72ee4a578659208aefcdd5e1>:0

Using https throws error while getting HttpResponseMessage from HttpClient.Result

I have following code in which a service in the controller calls a service in another controller :
[Route("Employees")]
[HttpGet]
public async Task<HttpResponseMessage> TCPEmployeeAsync()
{
StringBuilder uri = new StringBuilder();
uri.Append(ApiHelper.GetHost(this.Request));
uri.Append("/HumanResources/Employees");
uri.Append("?fields=id,fname,lname,email");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//This is where it gives error when uri contains https//
HttpResponseMessage response = client.GetAsync(uri.ToString()).Result;
return response;
}
This was just deployed in a DMZ server, and when we use http://localhost.... it works just fine but when we use https://example.domain.com/... it gives the following exception
System.Net.Sockets.SocketException: A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because c
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState
state, IAsyncResult asyncResult, Exception& exception)
What might be the problem? All my certificates are in place and up to date and also tried disabling TLS/SSL in the server, but that didn't work. Any help will be highly appreciated. Thanks.

Email sending service in c# doesn't recover after server timeout

I've been having this problem for months, and it's driving me nuts.
I have a windows service written in C# (.NET 4.5) which basically sends emails, using an outlook account (I think it's an office365 service). I'm aware of the "order of credentials" problem, which isn't affecting me (many emails send correctly).
The service starts correctly and begins sending emails. Sometimes when there's too many, I get a server error to wait, the service waits a few minutes and continues perfectly on its own.
In these cases I get Error A:
System.Net.Mail.SmtpException: The operation has timed out.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Cobranzas.WinService.Email.SendEmail(String subject, String body, String mailTo, String attPath)
at Cobranzas.WinService.CobranzasEmailService.SendEmails(IEnumerable`1 toSend, RepositoryEf emailRepo)
The problem: sometimes, and I haven't been able to find a pattern, it happens every few days, it gets a timeout error, and never recovers (restarting the services fixes it immediately). All subsequent sending tries fail with the same error. In this case, I get a mix of Error A and:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The operation has timed out.
at System.Net.ConnectionPool.Get(Object owningObject, Int32 result, Boolean& continueLoop, WaitHandle[]& waitHandles)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Cobranzas.WinService.Email.SendEmail(String subject, String body, String mailTo, String attPath)
at Cobranzas.WinService.CobranzasEmailService.SendEmails(IEnumerable`1 toSend, RepositoryEf emailRepo)
The logic of my service is as follows: I have a timer which every 5 minutes iterates over a lot of emails to be sent, and for each executes
Thread.Sleep(2000);
try
{
emailService.SendEmail(asunto, nuevoCuerpo, mail.Email, mail.AlertMessage.Attach);
}
catch (Exception ex)
{
if (ex is System.Net.Mail.SmtpException)
{
Thread.Sleep(20000); // Lo hacemos esperar 20 segundos
}
}
SendEmail method is:
var mailMessage = new MailMessage();
mailMessage.To.Add(mailTo);
mailMessage.Subject = subject;
mailMessage.Body = WebUtility.HtmlDecode(body);
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(emailFromAddress, emailFromName);
mailMessage.Headers.Add("Content-type", "text/html; charset=iso-8859-1");
// Attachment
if (attPath != null)
{
var data = new Attachment(attPath, MediaTypeNames.Application.Octet);
mailMessage.Attachments.Add(data);
}
var cred =
new NetworkCredential(emailFromAddress, emailFromPassword);
using (var mailClient =
new SmtpClient(emailSmtpClient, emailSmtpPort)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Timeout = 20000,
Credentials = cred
})
{
mailClient.Send(mailMessage);
}
foreach (Attachment attachment in mailMessage.Attachments)
{
attachment.Dispose();
}
The using SmtpClient, and attachment disposing are new, we added them trying to fix this. There was no behaviour change.
T̶h̶e̶ ̶T̶h̶r̶e̶a̶d̶.̶S̶l̶e̶e̶p̶ ̶a̶f̶t̶e̶r̶ ̶t̶h̶e̶ ̶t̶i̶m̶e̶o̶u̶t̶ ̶i̶s̶ ̶n̶e̶w̶ ̶a̶n̶d̶ ̶u̶n̶t̶e̶s̶t̶e̶d̶ ̶y̶e̶t̶.
Given that restarting the service fixes it, I'm suspecting something not being closed/cleaned appropriately, but I've checked and can't find what it could be. I found this link a while ago, but it looks pretty old.
Any help is much appreciated!
[PROGRESS]
I've tested the 20" wait after a timeout and nothing, it's still failing in the same way. Any ideas? We're really stumped with this.
I have the exact same problem. I found the solution here:
System.Net.WebException when issuing more than two concurrent WebRequests
http://www.wadewegner.com/2007/08/systemnetwebexception-when-issuing-more-than-two-concurrent-webrequests/
Basically, I changed the max number of connections allowed concurrently to a single external server. By default, according to that documentation it was 2. Although, it has a timeout (it waits sometime until one is released and then continues), at sometimes, it is not enough and it hangs.
<configuration>
<system.net>
<connectionManagement>
<add address="*" maxconnection="100" />
</connectionManagement>
</system.net>
</configuration>
I have not been able to find out how to recover after first timeout but hopefully this would get out "timeout" errors out of the way for some time.
Increasing the maximum number of connections may help, but I am not 100% sure if it won't postpone the issue until these number of connections have been reached. I decided to switch to MailKit instead. It has its own SMTP client implementation that is nearly a drop-in replacement and can work with the regular MailMessage object (if you depend on it). It doesn't use the connection pool at all, so it might be a more safe solution.

Cannot create a UdpClient on IPv6

What I thought would be a simple task, has turned into a bit of a nightmare.
What it boils down to now, is I need to create a UDP listener on port 8888, on a specific link local IPv6 address.
I get an exception thrown when the following line is executed:
_udpSoc = new UdpClient(MONITOR_INPUT_EVENT_SOCKET, AddressFamily.InterNetworkV6);
(where MONITOR_INPUT_EVENT_SOCKET is a const int of value 8888)
Having tried to look for support, I even find an MSDN article describing exactly the same line.
The SocketException thrown is "The requested address is not valid in its context" with an ErrorCode of 10049 with a stacktrace of:
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.UdpClient..ctor(Int32 port, AddressFamily family)
at [my code...]
Alternatively, if I change the problem line to:
_udpSoc = new UdpClient(_groupEp);
(where _groupEp is an IPEndPoint set to IPAddress.Any, with the ScopeId set the the correct interface, and port of MONITOR_INPUT_EVENT_SOCKET)
...and get an exception of "The requested address is not valid in its context", with the same ErrorCode and stack trace as before.
What's going wrong?

Async webrequest times out => Crashes IIS

I've got a web app, that gets data from external services. The request itself happens like the code below - quite straightforward as far as I can see. Create a request, fire it away asynchronously and let the callback handle the response. Works fine on my dev environment.
public static void MakeRequest(Uri uri, Action<Stream> responseCallback)
{
WebRequest request = WebRequest.Create(uri);
request.Proxy = null;
request.Timeout = 8000;
try
{
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith(task =>
{
WebResponse response = task.Result;
Stream responseStream = response.GetResponseStream();
responseCallback(response.GetResponseStream());
responseStream.Close();
response.Close();
});
} catch (Exception ex)
{
_log.Error("MakeRequest to " + uri + " went wrong.", ex);
}
}
However external test environments and the production environment could, for reasons beyond me, not reach the target URL. Fine, I thought - a request timeout won't really hurt anyone. However, it seemed that every time this request timed out, ASP.NET crashed and IIS was restarted. The event log shows me, among other things, this stacktrace:
StackTrace: at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.get_Result()
at MyApp.AsyncWebClient.<>c__DisplayClass2.<MakeRequest>b__0(Task`1 task)
at System.Threading.Tasks.Task`1.<>c__DisplayClass17.<ContinueWith>b__16(Object obj)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException: System.Net.WebException
Message: Unable to connect to the remote server
StackTrace: at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)
InnerException: System.Net.Sockets.SocketException
Message: 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
StackTrace: at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
..so it all boils down to a SocketException, it seems to me. And right afterwards (within the same second) another event (which I'm guessing is relevant) is logged:
Exception Info: System.AggregateException
Stack:
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
This is sort of beyond me as I'm no master of async code and threading, but that a timeout from a web requests causes IIS to crash seems very weird. I reimplemented MakeRequest to perform the requests synchronously, which works out great. The request still times out in those environments, but no damage is done and the app continues to run happily forever after.
So I've sortof solved my problem, but why does this happen? Can anyone enlighten me? :-)
Your continuation needs to handle the fact that .Result might reflect an exception. Otherwise you have an unhandled exception. Unhandled exceptions kill processes.
.ContinueWith(task =>
{
try {
WebResponse response = task.Result;
Stream responseStream = response.GetResponseStream();
responseCallback(responseStream);
responseStream.Close();
response.Close();
} catch(Exception ex) {
// TODO: log ex, etc
}
});
your old exception handler only covers the creation of the task - not the callback.

Categories

Resources