I'm trying to send email from Azure Web App using Office365. Later, we'll move it to Azure Web Job or Azure Functions.
The following sample code works in local development machine, as well as in Azure using on-premise SMTP server at same port 587. However, the same credentials as local machine throws the exception from smtp.office365.com in Azure.
It seems like the problem lies between Azure and Office 365. Any help would be greatly appreciated!
Sending email from an Azure App Service using an O365 SMTP server
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("To Email Address", "Benjamin"));
msg.From = new MailAddress("From Email Address", "You");
msg.Subject = "Azure Web App Email using smtp.office365.com";
msg.Body = "Test message using smtp.office365.com on Azure from a Web App";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("O365 UID", "O365 PASS");
client.Port = 587;
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg); <-- Line 34
Exception
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [XXXXX.namprd02.prod.outlook.com] at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at line 34