- Problem: The code runs fine in Dev and staging environments but not after deployment to azure, to an app service. Since it’s connecting fine to the email server in the dev/staging environments I’m guessing its a configuration problem in Azure.
What I have done so far with no results:
- Changing the app service TLS versions in azure.
- Updated Mailkit.
- Checked the server certificate callback of the SmtpClient.
- Trying different account credentials.
- using port 587 or 465.
- Extending the timeout period.
Code (Fails on the connect method):
public async Task<SmtpClient> GetSmtpClient()
{
SmtpClient client = new();
try
{
await client.ConnectAsync(smtpAddress, port, MailKit.Security.SecureSocketOptions.Auto);
await client.AuthenticateAsync(username, password);
}
catch (Exception)
{
throw;
}
return client;
}
Results in:
Exception: 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.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
--- End of stack trace from previous location ---
At the end:
- I’m trying to get this to run on the azure app service.
- The exception occurs due to timeout when trying to connect to the email server which does not happen in dev/staging envs. So maybe the email server is not accepting connection from azure for some reason, resulting in socketError.
I really appreciate any clues you can give me. All the best.
2
Answers
This problem turned out to be the mail server blocking the IP of the webapp. It was not clear why this IP was blocked. After they unblocked the Ip the Smtp client connected without issues and all was good again.
The error seems that your app service doesn’t have access to access the mail server. So you need to configure the rule to provide access. Check https://learn.microsoft.com/en-us/azure/app-service/app-service-ip-restrictions which have steps to check rules and add new rule to allow.