2014-09-23 32 views
1

我一直在尋找一種方式來驗證使用谷歌的服務的IMAP會話佔IMAP OAuth2和奇爾卡特

但既然我們已經使用奇爾卡特我們怎麼辦呢,我發現:

http://www.cknotes.com/imap-authentication-using-oauth/

讓我送原始命令:

imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");

這顯示瞭如何strucure的COMM和: https://developers.google.com/gmail/xoauth2_protocol

但是很難把它放在一起。

limilabs把東西放在一起很好地在這個例子: http://www.limilabs.com/blog/oauth2-gmail-imap-service-account

他們有一個整潔的imap.LoginOAUTH2(userEmail, credential.Token.AccessToken);一個包裝的東西成一個命令。我如何將它作爲Chilkat的原始命令?

回答

0
const string serviceAccountEmail = "[email protected]"; 
const string serviceAccountCertPath = @"service-xxxxxx.p12"; 
const string serviceAccountCertPassword = "notasecret"; 
const string userEmail = "[email protected]"; 



     X509Certificate2 certificate = new X509Certificate2(
      serviceAccountCertPath, 
      serviceAccountCertPassword, 
      X509KeyStorageFlags.Exportable); 

     ServiceAccountCredential credential = new ServiceAccountCredential(
      new ServiceAccountCredential.Initializer(serviceAccountEmail) 
      { 
       Scopes = new[] { "https://mail.google.com/" }, 
       User = userEmail 
      }.FromCertificate(certificate)); 

     bool success = credential.RequestAccessTokenAsync(CancellationToken.None).Result; 

     using (Chilkat.Imap imap = new Chilkat.Imap()) 
     { 
      imap.UnlockComponent("unlock-code"); 
      imap.Ssl = true; 
      imap.Port = 993; 
      imap.Connect("imap.gmail.com"); 



      var authString = String.Format("user={0}" + "\x001" + "auth=Bearer {1}" + "\x001" + "\x001",userEmail, credential.Token.AccessToken); 

      var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString)); 

      string response = imap.SendRawCommand("AUTHENTICATE XOAUTH2 " + encoded); 

      imap.SelectMailbox("Inbox"); 
      bool bUid; 
      bUid = false; 
      string mimeStr; 
      int i; 
      int n; 
      n = imap.NumMessages; 
      for (i = 1; i <= n; i++) 
      { 

       // Download the email by sequence number. 
       mimeStr = imap.FetchSingleAsMime(i, bUid); 


       Chilkat.Email chilkatEmail = new Chilkat.Email(); 
       chilkatEmail.SetFromMimeText(mimeStr); 
       Console.WriteLine(chilkatEmail.Subject); 
      } 


      imap.CloseMailbox("Inbox"); 

      Console.ReadLine(); 
     } 
    }