I am trying to send an email via SmtpClient ("smtp.office365.com") and am running into issues.
Consider the following code snippet:
var fromAddress = new MailAddress("someone@example.com", "TestFrom");
var toAddress = new MailAddress("someoneto@example.com", "TestSend");
string fromPassword = "SomePassword";
var smtp = new SmtpClient
{
Host = "smtp.office365.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = "Hey There Did this Test Work?",
Body = "Hey There Did this Test Work?",
IsBodyHtml = true,
})
smtp.Send(message);
This code works correctly from a .Net console application. I can also use the same credentials and send an email via PowerShell.
When I attempt to use the same code snippet in an Asp.Net application, it fails. I've tried this with the application deployed locally and to Azure. I get the same results.
I get the following exceptions:
Failure sending mail. Unable to read data from the transport connection: net_io_connectionclosed.
I am told that used to work correctly at some point previous to the past 3 months. Am I doing something wrong here? Are there additional configuration settings I should be using? Does Asp.Net require something to bet set up (locally and within Azure) in order for this to work?
Thx
We had similar issues sending emails and it turned out that it was because we weren't enforcing TLS 1.2. You can enforce it with following code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
You only need call it once in your application, so Application_Start callback in global.asax is one possible place to put it.