Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use default network credentials with Mailkit and Exchange?

I'd like to use MailKit to send an email through our Exchange server, using the credentials of the process.

Building up a NetworkCredential with domain/username/password works:

using (var client = new SmtpClient(ProtocolLogger))
{
    client.Connect(server, port);

    // Works
    var creds = new NetworkCredential(username, password, domain);
    client.Authenticate(creds);

    client.Send(msg);        
}

If I use CredentialCache.DefaultNetworkCredentials while running as the same user, it fails with a MailKit.Security.AuthenticationException:

using (var client = new SmtpClient(ProtocolLogger))
{
    client.Connect(server, port);

    // Authentication failure
    client.Authenticate(CredentialCache.DefaultNetworkCredentials);

    client.Send(msg);        
}

The ProtocolLogger output the following (with mail server and base64 encoded strings changed):

Connected to smtp://mymailserver:25/?starttls=when-available
S: 220 mymailserver Microsoft ESMTP MAIL Service ready at Thu, 30 Jun 2016 12:45:04 +0930
C: EHLO [172.1.1.2]
S: 250-mymailserver Hello [172.1.1.2]
S: 250-SIZE 51200000
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-X-ANONYMOUSTLS
S: 250-AUTH NTLM LOGIN
S: 250-X-EXPS GSSAPI NTLM
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250-XEXCH50
S: 250 XRDST
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [172.1.1.2]
S: 250-mymailserver Hello [172.1.1.2]
S: 250-SIZE 51200000
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH NTLM LOGIN
S: 250-X-EXPS GSSAPI NTLM
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250-XEXCH50
S: 250 XRDST
C: AUTH NTLM {EncodedStringRemoved}
S: 334 {EncodedStringRemoved}
C: {EncodedStringRemoved}
S: 535 5.7.3 Authentication unsuccessful
C: AUTH LOGIN
S: 334 {EncodedStringRemoved}
C: 
S: 334 {EncodedStringRemoved}
C: 
S: 334 {EncodedStringRemoved}
C: QUIT
S: 334 {EncodedStringRemoved}

It's worth noting that System.Net.Mail.SmtpClient uses DefaultNetworkCredentials when setting the UseDefaultCredentials property to true, and this works for me. I want to use MailKit because of the extra features like ProtocolLogging though.

like image 997
JamesD Avatar asked Jun 30 '16 03:06

JamesD


1 Answers

You cannot use CredentialCache.DefaultNetworkCredentials with MailKit because when MailKit asks the credential to provide the username and password strings that it needs to send to the server, the DefaultNetworkCredentials tells MailKit that the username and password strings are empty and so MailKit tries to authenticate with empty strings.

System.Net.Mail seems to be able to use an internal API to get the real strings that MailKit does not have access to.

like image 139
jstedfast Avatar answered Sep 20 '22 19:09

jstedfast