2014-12-01 228 views
0

我正嘗試使用MailKit(http://jstedfast.github.io/MailKit/docs/index.html)使用oAuth登錄Gmail。我能夠使用刷新的AuthToken登錄到Google API,但是當我嘗試在MailKit中使用刷新的令牌時,出現「無效憑證」錯誤如何使用MailKit登錄到Gmail IMAP

任何線索? 謝謝, 傑夫

這裏是我的代碼:

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("[email protected]", tokenResponse.AccessToken); 

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

       throw; 
      } 


     } 
+0

OAUTH2需要一個自定義的認證流程,它不能使用標準的IMAP認證,這是看起來正在做的事情。它看起來像你傳遞訪問令牌作爲密碼,事實並非如此。 – Max 2014-12-01 21:20:33

+0

實際上,在MailKit中,我認爲它是作爲密碼傳入的。這是一個使用SMTP的另一個答案的鏈接,但仍然不起作用。我將研究我的AuthCode可能無法使用我需要的範圍構建的範圍。我剛剛發現https://mail.google.com用於IMAP訪問。我只能從API讀取訪問權限。直到現在才意識到它是不同的。無論如何,這裏是鏈接@Max。 [link](http://stackoverflow.com/questions/24195508/smtp-and-oauth-2/24204968#24204968) – Jeff 2014-12-02 05:18:18

回答

0

一個更清晰的答案是,範圍是不正確的原始代碼中

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

必須

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

爲了使用一個訪問令牌IMAPI進行身份驗證。

0

這只是一個範圍問題。上面的代碼適用於gmail oAuth!

+0

什麼是'connection'變量? – 2016-01-19 10:09:24

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」選項。這一定會奏效。