【问题标题】:How to send email by using MailKit?如何使用 MailKit 发送电子邮件?
【发布时间】:2015-11-03 10:06:28
【问题描述】:

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

我想用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);
}

但我有An exception of type 'MailKit.Security.AuthenticationException' occurred in MailKit.dll but was not handled in user code.Additional information: Authentication failed.

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

我该如何解决?

【问题讨论】:

  • 这不是关于 mailkit 或 C#,而是关于 Google。要么密码错误,要么需要更改账号as shown here的安全设置
  • 我相信这是因为您需要设置与 Oauth 2.0 的连接 github.com/jstedfast/MailKit/blob/…
  • 实际上,即使密码看起来正确,GMail 也会返回身份验证错误的原因有多种 - 一次密码,两次身份验证as described here

标签: c# gmail mailkit


【解决方案1】:

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

完成此操作后,获取访问令牌的最简单方法是使用 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

现在您有了访问令牌 (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

【讨论】:

  • 我可以将邮件发送到“无 gmail”帐户吗?
  • 您不能将 Google 的 OAuth2 令牌用于非 GMail 服务器。你问的是这个吗?
  • 我应该怎么做才能发送电子邮件到no_gmail@yandex.ru?
  • 使用常规的用户名和密码。
  • 如果我使用 System.Net.Mail 但使用 X509Certificate2 我会遇到新的谷歌安全政治问题吗?
【解决方案2】:

测试了以下代码并为我工作:

        // STEP 1: Navigate to this page https://www.google.com/settings/security/lesssecureapps & set to "Turn On"

        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("Joey Tribbiani", "YOU_FROM_ADDRESS@gmail.com"));
        message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "YOU_TO_ADDRESS@gmail.com"));
        message.Subject = "How you doin'?";

        message.Body = new TextPart("plain")
        {
            Text = @"Hey Chandler,I just wanted to let you know that Monica and I were going to go play some paintball, you in?-- Joey"
        };

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


            // Note: since we don't have an OAuth2 token, disable
            // the XOAUTH2 authentication mechanism.
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            // Note: only needed if the SMTP server requires authentication
            client.Authenticate("YOUR_GMAIL_NAME", "YOUR_PASSWORD");

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

【讨论】:

  • 我已经试过了,但我仍然收到证书错误,还有其他人遇到过这个问题吗?
  • 非常适合我。非常适合学生项目!在尝试此代码之前,请不要忘记访问此链接! :google.com/settings/security/lesssecureapps
  • 所以任何破解你程序的人都会看到你的谷歌邮件密码?对我来说似乎不是一个好主意!
  • 对我有用。我在其中使用了我的测试应用程序 - 使用我的测试 gmail 帐户。在生产中,我使用了我的客户端电子邮件的 smtp 服务器。所以其他程序员(或最糟糕的黑客)看到我的“应用程序密码”没有问题 - 这只是一个 gmail 测试帐户,我可以随时撤销此应用程序密码。
猜你喜欢
  • 2023-03-18
  • 2017-02-17
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2020-01-17
  • 2019-10-14
  • 2021-03-13
相关资源
最近更新 更多