我想使用MailKit通过我们的Exchange服务器发送电子邮件,使用该进程的凭据.
使用域/用户名/密码构建NetworkCredential:
using (var client = new SmtpClient(ProtocolLogger)) { client.Connect(server,port); // Works var creds = new NetworkCredential(username,password,domain); client.Authenticate(creds); client.Send(msg); }
如果我在以同一用户身份运行时使用CredentialCache.DefaultNetworkCredentials,则会因MailKit.Security.AuthenticationException而失败:
using (var client = new SmtpClient(ProtocolLogger)) { client.Connect(server,port); // Authentication failure client.Authenticate(CredentialCache.DefaultNetworkCredentials); client.Send(msg); }
ProtocolLogger输出如下(邮件服务器和base64编码的字符串已更改):
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}
值得注意的是,System.Net.Mail.SmtpClient在将UseDefaultCredentials属性设置为true时使用DefaultNetworkCredentials,这对我有用.我想使用MailKit,因为ProtocolLogging等额外的功能.