3
votes

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

1

1 Answers

2
votes

You must modify your DNS records (SPF) on the domain of the expeditor.

For exemple if the expeditor is [email protected].

You must verify the DNS TXT record of "mydomain.com", it must containt :

v=spf1 include:spf.protection.outlook.com -all

You can check you DNS record with this website : https://www.whois.com.au/whois/dns.html

Enter your domain and click the button "Do live DNS lookup", the DNS records will appears.

enter image description here

If there is not this TXT, your must modify it...

Look this link : https://answers.microsoft.com/en-us/msoffice/forum/msoffice_outlook-mso_winother-mso_o365b/client-was-not-authenticated-to-send-anonymous/d405bcb0-f40c-42fa-b1b2-477597100123