I have been attempting to utilise Office 365' SMTP functionality, but have run into difficulties when trying to authenticate with it.
This is the code I'm testing with:
string host = "smtp.office365.com";
int port = 587;
string username = "<redacted>";
string password = "<redacted>";
var client = new SmtpClient(new ProtocolLogger("C:\\temp\\mailerLog.log"));
client.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
{
client.Authenticate(new NetworkCredential(username, password));
}
Now, although I have obviously removed the credentials from this example, those credentials are absolutely the ones that I can copy and paste to log into outlook.office365.com
in a web browser with no issues.
When running the above however, a MailKit.Security.AuthenticationException
is thrown with the following message (I've redacted the parts that may be identifying information):
535: 5.7.3 Authentication unsuccessful [<redacted>.<redacted>.PROD.OUTLOOK.COM]
The InnerException
is of type MailKit.Net.Smtp.SmtpCommandException
and has a StatusCode
of AuthenticationInvalidCredentials
, which suggests the credentials must be wrong somehow...but why? What could/should the credentials be for office 365 other than the account itself? What am I doing wrong?
I feel like there must be a step I'm missing, such as something that needs configuring in Office365, but after trawling the Admin panel, I'm not sure what it could be.
I've also tried having a look at what gets logged, but it doesn't seem to reveal that much to me. I've included it below (with identifying information redacted) in case someone more familiar with SMTP notices something which reveals what's wrong:
Connected to smtp://smtp.office365.com:587/?starttls=when-available
S: 220 <redacted>.outlook.office365.com Microsoft ESMTP MAIL Service ready at Fri, 27 Sep 2019 20:52:52 +0000
C: EHLO [192.168.1.17]
S: 250-<redacted>.outlook.office365.com Hello [<redacted>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.1.17]
S: 250-<redacted>.outlook.office365.com Hello [<redacted>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH LOGIN
S: 334 VXNlcm5hbWU6
C: <redacted>
S: 334 UGFzc3dvcmQ6
C: <redacted>
S: 535 5.7.3 Authentication unsuccessful [<redacted>.<redacted>.PROD.OUTLOOK.COM]
Also, I do not believe this question is a duplicate, as whilst there are other similar questions on Stackoverflow, they either use Microsoft's deprecated System.Net.Mail.SmtpClient
or involve full-fledged Exchange servers where server-side configuration is readily available (unless I've missed something somewhere).