首页 > 解决方案 > 如何在没有用户交互的情况下使用 GMail API 创建草稿

问题描述

我有一个 C# 程序在无人值守的无头服务器上运行。

我需要该程序能够在我的 GMail 帐户中发送电子邮件和创建草稿电子邮件。

因此,我需要一个永久密钥或授权令牌供程序用来访问我的 GMail 帐户。

我一直在大量的 GMail API 文档中看到提示,这是可能的,但我找不到任何关于如何创建这样的密钥或令牌的实际说明。

标签: c#gmail-apigoogle-workspacegoogle-api-dotnet-clientservice-accounts

解决方案


好吧,我最终在https://developers.google.com/identity/protocols/oauth2/service-account找到了说明

您创建一个服务帐户,为其提供适当范围的域范围权限(请参阅https://developers.google.com/gmail/api/auth/scopes),并在 json 文件中下载私钥(我称为 mine server_credentials.json) .

然后,在您的程序中,您执行以下操作:

GmailService getService() {

    GoogleCredential credential;

    try {
        using (var stream = new FileStream(@"server_credentials.json", FileMode.Open, FileAccess.Read)) {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(GmailService.Scope.GmailCompose)
                .CreateWithUser("me@example.com");
        }
        return new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Jumbo Accounts" });
    } catch(Exception ex) {
        throw new ApplicationException("Error logging into Google Mail", ex);
    }
}

附加参考:

Gmail API 有一个示例快速入门参考列表,可以指导您如何启用 API、创建凭据甚至是示例代码,具体取决于您首选的编程语言。例如:.NET quickstart创建项目并启用 API创建凭据


推荐阅读