SMTP 5.7.57 error when trying to send email via Office 365

Rowland Shaw picture Rowland Shaw · Mar 2, 2016 · Viewed 42.5k times · Source

I'm trying to set up some code to send email via Office 365's authenticated SMTP service:

var _mailServer = new SmtpClient();
_mailServer.UseDefaultCredentials = false;
_mailServer.Credentials = new NetworkCredential("[email protected]", "password");
_mailServer.Host = "smtp.office365.com";
_mailServer.TargetName = "STARTTLS/smtp.office365.com"; // same behaviour if this lien is removed
_mailServer.Port = 587;
_mailServer.EnableSsl = true;

var eml = new MailMessage();
eml.Sender = new MailAddress("[email protected]");
eml.From = eml.Sender;
eml.to = new MailAddress("[email protected]");
eml.Subject = "Test message";
eml.Body = "Test message body";

_mailServer.Send(eml);

This doesn't appear to be working, and I'm seeing an exception:

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
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)

I've tried enabling network tracing and it appears that secure communications are established (for example, I see a line in the log for the "STARTTLS" command, and later there's a line in the log "Remote certificate was verified as valid by the user.", and the following Send() and Receive() data is not readable as plain text, and doesn't appear to contain any TLS/SSH panics)

I can use the very same email address and password to log on to http://portal.office.com/ and use the Outlook email web mail to send and read email, so what might be causing the authentication to fail when sending email programmatically?

Is there any way to additionally debug the encrypted stream?

Answer

Matteo Conta picture Matteo Conta · Jan 10, 2017

In my case after I tried all this suggestion without luck, I contacted Microsoft support, and their suggestion was to simply change the password.

This fixed my issue.

Note that the password wasn't expired, because I logged on office365 with success, however the reset solved the issue.

Lesson learned: don't trust the Office 365 password expiration date, in my case the password would be expired after 1-2 months, but it wasn't working. This leaded me to investigate in my code and only after a lot of time I realized that the problem was in the Office365 password that was "corrupted" or "prematurely expired".

Don't forget every 3 months to "refresh" the password.