11
votes

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?

10
is the address specified in eml.From = eml.Sender; the same as the email address of the account you are connecting to? If you change the email address specified in the From field to be that of the account, does the email send successfully? If so, it is probably the case that the SMTP is configured to fail to send emails which look like they come from a different account.user1666620
It still fails if only the From is set, and no Sender is specified. In all cases, the From matches the NetworkCredentialsRowland Shaw
I'm out of ideas in that case, since otherwise your code looks fine. If you do find a solution, can you post it here? Am interested in finding out what the cause is.user1666620
Client was not authenticated to send anonymous mail during MAIL FROM says that you are trying to send anonymous mail, which means it does not recognize your From address.jstedfast
@jstedfast why would it not recognise the sender, when I can log in to Office 365 with it?Rowland Shaw

10 Answers

5
votes

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.

4
votes

To aid in debugging, try temporarily switching to MailKit and using a code snippet such as the following:

using System;

using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("", "[email protected]"));
            message.To.Add (new MailboxAddress ("", "[email protected]"));
            message.Subject = "Test message";

            message.Body = new TextPart ("plain") { Text = "This is the message body." };

            using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) {
                client.Connect ("smtp.office365.com", 587, SecureSocketOptions.StartTls);

                client.Authenticate ("[email protected]", "password");

                client.Send (message);
                client.Disconnect (true);
            }
        }
    }
}

This will log the entire transaction to a file called "smtp.log" which you can then read through and see where things might be going wrong.

Note that smtp.log will likely contain an AUTH LOGIN command followed by a few commands that are base64 encoded (these are your user/pass), so if you share the log, be sure to scrub those lines.

I would expect this to have the same error as you are seeing with System.Net.Mail, but it will help you see what is going on.

Assuming it fails (and I expect it will), try changing to SecureSocketOptions.None and/or try commenting out the Authenticate().

See how that changes the error you are seeing.

3
votes

Be sure you're using the actual office365 email address for the account. You can find it by clicking on the profile button in Outlook365. I wrestled with authentication until I realized the email address I was trying to use for authentication wasn't the actual mailbox email account. The actual account email may have the form of: [email protected].

2
votes

We got ours working by converting the mailboxes (from address) from "shared" to "regular". Before this change, my application quit sending email when we migrated from Gmail to Office 365. No other code changes were required, besides setting the host to smtp.office365.com.

1
votes

Please check below code I have tested to send email using Exchange Online:

        MailMessage msg = new MailMessage();
        msg.To.Add(new MailAddress("[email protected]", "XXXX"));
        msg.From = new MailAddress("[email protected]", "XXX");
        msg.Subject = "This is a Test Mail";
        msg.Body = "This is a test message using Exchange OnLine";
        msg.IsBodyHtml = true;

        SmtpClient client = new SmtpClient();
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "YourPassword");
        client.Port = 587; // You can use Port 25 if 587 is blocked
        client.Host = "smtp.office365.com";
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        try
        {
            client.Send(msg);

        }
        catch (Exception ex)
        {

        }

enter image description here Port (587) was defined for message submission. Although port 587 doesn't mandate requiring STARTTLS, the use of port 587 became popular around the same time as the realisation that SSL/TLS encryption of communications between clients and servers was an important security and privacy issue.

1
votes

In my case my problem was not related to the code but something to do with the Exchange mailbox. Not sure why but this solved my problem:

  • Go to the exchange settings for that user's mailbox and access Mail Delegation
  • Under Send As, remove NT AUTHORITY\SELF and then add the user's account.

This gives permissions to the user to send emails on behalf of himself. In theory NT AUTHORITY\SELF should be doing the same thing but for some reason that did not work.

Source: http://edudotnet.blogspot.com.mt/2014/02/smtp-microsoft-office-365-net-smtp.html

1
votes

I got this same error while testing, using my own domain email account during development. The issue for me seemed related to the MFA (Multi Factor Authentication) that's enabled on my account. Switching to an account without MFA resolved the issue.

1
votes

I had this issue since someone had enabled Security defaults in Azure. This disables SMTP/Basic authentication. It's clearly stated in the documentation, but it's not evident by the error message, and you have to have access to the account to find out.

https://docs.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults

It's possible to enable it per account. https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission

0
votes

You need change the credentials function. Here is the substitution you need to make:

change

-*_mailServer.Credentials = new NetworkCredential("[email protected]", "password");*

for this

-*_mailServer.Credentials = new NetworkCredential("[email protected]", "password", "domain");*
0
votes

In my case, password was expired.I just reset password and its started working again