Search code examples
c#asp.net-coreemailsmtpclient

Getting an error when trying send an email using SmtpClient in asp.net core application


I am trying to send an email from asp.net core application but I keep getting an error that reads

SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail. [JN2P275CA0038.ZAFP275.PROD.OUTLOOK.COM]

I have also tried checking firewall rules and increasing timeout and that has not helped so I am not sure what is wrong

This is my code to send email

   SmtpClient client = new SmtpClient("smtp.office365.com")
                    {
                        //Port = 587, //outlook port 587
                        Port = 587, 
                        EnableSsl = true,
                        //UseDefaultCredentials
                        UseDefaultCredentials = false,
                        TargetName = "STARTTLS/smtp.office365.com",
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential("[email protected]","password"),
                    };

                    MailMessage message = new MailMessage()
                    {
                        From = new MailAddress("[email protected]"),
                        Subject = "New Requisition",
                        Body = "New requisition has been created:" + " " + requisition.RequisitionNo,
                        IsBodyHtml = true,
                    };

                    message.To.Add(SubmissionNotfication.To);
                    //message.CC.Add(SubmissionNotfication.Cc);
                    //var attachment = new System.Net.Mail.Attachment(filePath); //Attachment(string fileName, string mediaType) 
                    //message.Attachments.Add(attachment);
                    client.Send(message);
                }
        

Solution

  • Have a look at How to set up an application to send email using Microsoft 365 or Office 365

    You might have to use your MX endpoint as the sending domain and try port 25

    SmtpClient client = new SmtpClient("yourorganisation.mail.protection.outlook.com")
    {
        Port = 25, 
        EnableSsl = true,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential("[email protected]","password"),
    };