我一直在寻找一种通过谷歌服务帐户验证IMAP会话的方法
但是既然我们已经使用了Chilkat,我们是如何做到的,我找到了以下内容:
http://www.cknotes.com/imap-authentication-using-oauth/
允许我发送原始命令:
imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");
这显示了如何构造命令: 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 :(得分:0)
const string serviceAccountEmail = "service-account-xxxxxx@developer.gserviceaccount.com";
const string serviceAccountCertPath = @"service-xxxxxx.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "user@domain.com";
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();
}
}