c# - 如何使用 MailKit 发送电子邮件?

标签 c# gmail mailkit

根据新的谷歌政治https://googleonlinesecurity.blogspot.de/2014/04/new-security-measures-will-affect-older.html我无法发送电子邮件。 “不太安全的应用程序”被谷歌认为是不使用 OAuth 2.0 的应用程序。

我想用MailKit来解决这个问题

var message = new MimeMessage();

message.From.Add(new MailboxAddress("Joey Tribbiani", "noreply@localhost.com"));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "mymail@gmail.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain"){ Text = @"Hey" };

using (var client = new SmtpClient())
{
   client.Connect("smtp.gmail.com", 587);

   ////Note: only needed if the SMTP server requires authentication
   client.Authenticate("mymail@gmail.com", "mypassword");

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

但我得到了MailKit.dll 中发生了类型为“MailKit.Security.AuthenticationException”的异常,但未在用户代码中处理。其他信息:身份验证失败。

我不想更改我的安全设置。因为我希望一切都是安全的。这就是为什么我开始使用 MailKit 而不是 System.Net.Mail

我该如何解决?

最佳答案

您需要做的第一件事是关注Google's instructions为您的应用程序获取 OAuth 2.0 凭据。

完成后,获取访问 token 的最简单方法是使用 Google 的 Google.Apis.Auth图书馆:

var certificate = new X509Certificate2 (@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
    .Initializer ("your-developer-id@developer.gserviceaccount.com") {
    // Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
    Scopes = new[] { "https://mail.google.com/" },
    User = "username@gmail.com"
}.FromCertificate (certificate));

//You can also use FromPrivateKey(privateKey) where privateKey
// is the value of the field 'private_key' in your serviceName.json file

bool result = await credential.RequestAccessTokenAsync (cancel.Token);

// Note: result will be true if the access token was received successfully

现在您有了访问 token (credential.Token.AccessToken),您可以将它与 MailKit 一起使用,就好像它是密码一样:

using (var client = new SmtpClient ()) {
   client.Connect ("smtp.gmail.com", 587);

   // use the OAuth2.0 access token obtained above
   var oauth2 = new SaslMechanismOAuth2 ("mymail@gmail.com", credential.Token.AccessToken);
   client.Authenticate (oauth2);

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

更新:

上述解决方案适用于 Google 所指的用于服务器到服务器通信的“服务帐户”,但如果您希望 OAuth2 支持标准电话或桌面应用程序,例如,您需要遵循我在这里写的说明:https://github.com/jstedfast/MailKit/blob/master/GMailOAuth2.md

关于c# - 如何使用 MailKit 发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496290/

相关文章:

c# - 这两种在autofac中注册实例的方式有什么区别

email - 显示/隐藏 Gmail 电子邮件正文中的内容

python - Gmail Python 多个附件

linux - MailKit.Net.Smtp.SmtpClient.Send 无法在 Linux 上运行

c# - 在 MailKit 中,如何获取邮件的原始表示形式?

c# - 如何在asp上调用javascript函数和c#代码:button?

c# - 处理对象时避免重复编码

c# - 如何以编程方式订阅对象的所有事件?

php - 我已经尝试了一切、每种技术,但我无法从我的 xampp 服务器发送 gmail?

c# - MailKit 设置 Append 后可见的 MessageFlag