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

Viewed 1344

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("myemail@myemails.com","password"),
                    };

                    MailMessage message = new MailMessage()
                    {
                        From = new MailAddress("myemail@myemails.com"),
                        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);
                }
        
2 Answers

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("myemail@myemails.com","password"),
};

It could be few reasons you encounter above error message

  1. Incorrect email usernmae and password
  2. SSL settings. Make sure you enable SSL security while sending emails through your application
  3. Your port issue. Make sure that your ISP doesn't block port 25 or 587. You can check it by using telnet.

You may need to check tutorial about send email using outlook. If you are using Gmail, then you can refer to this post https://dotnetblog.asphostportal.com/using-gmail-to-send-email-in-asp-net-core/

Related