1

我正在尝试使用 MailKit ( http://jstedfast.github.io/MailKit/docs/index.html ) 使用 oAuth 登录 Gmail。我可以使用刷新的 AuthToken 登录 Google API,但是当我尝试在 MailKit 中使用刷新的令牌时,我收到错误“Invalid Credentials”

有什么线索吗??谢谢,杰夫

这是我的代码:

 var secrets = new ClientSecrets()
        {
            ClientId = "xxx-yyy.apps.googleusercontent.com",
            ClientSecret = "xyzSecret"
        };

        IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = secrets,
                    Scopes = new string[] { GmailService.Scope.GmailReadonly }
                });

        var tokenResponse = flow.RefreshTokenAsync("", connection.RefreshToken, CancellationToken.None).Result;

        using (var client = new MailKit.Net.Imap.ImapClient())
        {
            var credentials = new NetworkCredential("emailtoconnect@gmail.com", tokenResponse.AccessToken);

            client.Connect("imap.gmail.com", 993, true, CancellationToken.None);
            try
            {
                client.Authenticate(credentials, CancellationToken.None);
            }
            catch (Exception ex)
            {

                throw;
            }


        }
4

3 回答 3

1

更明确的答案是原始代码中的范围不正确

Scopes = new string[] { GmailService.Scope.GmailReadonly }

需要是

Scopes = new string[] { GmailService.Scope.MailGoogleCom }

为了使用访问令牌向 imapi 进行身份验证。

于 2017-07-16T06:50:06.063 回答
0

这只是一个范围问题。上面的代码适用于 gmail oAuth!

于 2014-12-02T14:27:17.887 回答
0
using (var client = new ImapClient())
            {
                client.Connect("imap.gmail.com", 993, true);  
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(EmailId, Password);
            }

上面这段代码用于使用 imap 和 MailKit 工具登录 gmail。但在此之前,您必须手动登录 gmail 并在“设置”中选中“启用 Imap”选项。这肯定会奏效。

于 2016-06-30T09:35:12.890 回答