使用Gmail API阅读其他用户的电子邮件

时间:2020-08-31 10:37:42

标签: c# google-api google-oauth gmail-api google-api-dotnet-client

我正在编写一个C#桌面应用程序,我想在其中读取用户的所有电子邮件(然后是我的)。我已经在GMail控制台上创建了一个项目。当我阅读自己的电子邮件时,该应用程序可以正常运行,但是我无法阅读其他用户的电子邮件/消息。 GMail文档中提供的示例代码可以读取所有者电子邮件ID的标签,但可以读取其他用户的标签(使用GMail电子邮件ID /个人资料ID)

GMail Example

UserCredential credential;

using (var stream = new FileStream("CredentialFile.json", FileMode.Open, FileAccess.Read))
{
    // The file token.json stores the user's access and refresh tokens, and is created
    // automatically when the authorization flow completes for the first time.
    string credPath = "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "user",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
    Console.WriteLine("Credential file saved to: " + credPath);
}

logMe("Token : " + credential.Token.AccessToken);

// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
});


// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("XXXXXXXXXXXXXXXXXXXXX");

// List labels.
IList<Label> labels = request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
    foreach (var labelItem in labels)
    {
        Console.WriteLine("{0}", labelItem.Name);
    }
}
else
{
    Console.WriteLine("No labels found.");
}

Console.Read();

1 个答案:

答案 0 :(得分:1)

FileDataStore以%appData%的形式存储已登录用户的凭据,以您作为“用户”提供的用户名表示

如果要更改用户,则需要将当前登录的用户更改为其他用户。它只是一个字符串,因此它可以是您想要表示此用户的任何内容。然后让用户使用其帐户登录。

如果您想了解FileDataStore的工作原理,这可能会让您Google .net – FileDatastore demystified

感兴趣
相关问题