I have an ASP.net MVC5 app that uses Office365 to send emails to users, that gives the following exception, the runtime version is 4.5.2
when I tried it in a new project with runtime version 4.8, it worked fine with no Errors, how to migrate this code to older runtime versions
public string SendEmail()
{
MailAddress toAddress = new MailAddress("test2@test.com", "Test");
const string subject = "Outlook Test";
const string HtmlBody = "This is our outlook Test";
SendConEmail(toAddress, subject, HtmlBody);
return "Email successfully Sent";
}
public static void SendConEmail(MailAddress toAddress, string subject, string HtmlBody)
{
MailAddress fromAddress = new MailAddress("test@test.com", "Test");
const string fromPassword = "PAssword Here";
var smtp = new SmtpClient
{
// Host = "smtp-mail.outlook.com",
Host = "smtp.office365.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
};
try
{
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = HtmlBody,
IsBodyHtml = true
})
{
smtp.Send(message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Since you say the code works in 4.8 but not in 4.5.2, this is most likely a TLS problem.
Apps which target .NET Framework 4.7 or later automatically use the default security protocols defined by the operating system. Apps which target .NET Framework 4.5.2 require a registry setting, and potentially a hotfix, to do the same.
(The hotfix doesn't apply if the computer already has a later version of .NET Framework installed.)
However, the simplest and recommended option is to upgrade your app to target at least .NET Framework 4.7.2, and preferably 4.8.