【问题标题】:How to use GMail API to create drafts without user interaction如何在没有用户交互的情况下使用 GMail API 创建草稿
【发布时间】:2021-07-09 18:21:56
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# gmail-api google-workspace google-api-dotnet-client service-accounts


    【解决方案1】:

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

    您创建一个服务帐户,为它授予适当范围的域范围权限(请参阅https://developers.google.com/gmail/api/auth/scopes),然后在 json 文件中下载一个私钥(我叫我的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 有一个示例 Quickstart 参考列表,可以根据您的首选编程语言指导您如何启用 API、创建凭据甚至是示例代码。例如:.NET quickstartCreate a project and enable the APICreate credentials

    【讨论】:

    • 请注意添加一些有关如何设置域范围委派到服务帐户的信息。
    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 2016-03-08
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多