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.