1

enter image description here

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);
    }
}
SaTech
  • 430
  • 6
  • 17
  • 1
    Can you share the code please? – Chetan Feb 15 '22 at 09:55
  • You're using Office365 to send the email; *"using Outlook"* makes it sound like you're using the Outlook desktop application, which wouldn't work in an ASP.NET application. – Richard Deeming Feb 15 '22 at 10:14
  • as i said it's already working in a brand new app, but the problem is that , it doesn't work in the original app ,besides i don't use the desktop app – SaTech Feb 15 '22 at 10:17
  • 1
    Does this answer your question? [Send SMTP email using System.Net.Mail via Exchange Online (Office 365)](https://stackoverflow.com/questions/6244694/send-smtp-email-using-system-net-mail-via-exchange-online-office-365) – Eugene Astafiev Feb 15 '22 at 10:28

1 Answers1

1

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.

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151