【问题标题】:CRON Node.js Gmail API scriptCRON Node.js Gmail API 脚本
【发布时间】:2016-12-31 12:32:31
【问题描述】:

如何正确设置发送电子邮件的 Gmail API 脚本?

我即将使用this method,并开始从this quickstart 指南构建我的脚本。

是否有其他方法可以在不使用 OAuth 2 验证的情况下执行此操作?还是一种一劳永逸的验证方式?

【问题讨论】:

    标签: node.js cron google-api gmail-api google-api-nodejs-client


    【解决方案1】:

    好吧,在您的应用中使用 Gmail API 时,您需要使用 OAuth 2.0,因为对 Gmail API 的所有请求都必须由经过身份验证的用户授权。如果您注意到 quickstart,这里有一个步骤,您需要创建凭据/Outh 客户端 ID 以使此 API 正常工作。

    欲了解更多信息,还有另一种方式authorize your app with Gmail。您可以借助 Google+ Sign-in 为您的应用提供“使用 Google 登录”身份验证方法的帮助。

    【讨论】:

    • 我将把这个脚本作为来自服务器的 CRON 执行。基本上它应该在特定的时间间隔自动执行。是否可以对我的电子邮件使用域范围委派并避免来自我们公司域内的其他帐户的身份验证?
    【解决方案2】:

    在向 GMail 请求授权时,OAuth 2.0 会提供一个访问令牌和一个刷新令牌。为避免每次都进行验证,请存储访问令牌。过期后使用刷新令牌获取新的访问令牌(访问令牌每隔一小时过期一次)。

    在此处了解此过程:https://developers.google.com/identity/protocols/OAuth2

    【讨论】:

      【解决方案3】:

      我找到了使用 JWT 授权 OAuth2 的解决方案。 您需要拥有管理员帐户才能创建域范围的委派服务帐户。然后在开发者控制台中,您需要下载作为凭据加载的服务密钥 JSON 文件。

      首先像这样获取所有用户:(这里你需要使用具有管理员目录权限的帐户)

      const google = require('googleapis');
      const gmail = google.gmail('v1');
      const directory = google.admin('directory_v1');
      const scopes = [
        'https://www.googleapis.com/auth/gmail.readonly',
        'https://www.googleapis.com/auth/admin.directory.user.readonly'
      ];
      const key = require('./service_key.json');
      
      var authClient = new google.auth.JWT(
        key.client_email,
        key,
        key.private_key,
        scopes,
        "authorized@mail.com"
      );
      
      authClient.authorize(function(err, tokens){
        if (err) {
          console.log(err);
          return;
        }
      
        directory.users.list(
          {
            auth: authClient,
            customer: 'my_customer',
            maxResults: 250,
            orderBy: 'email'
          }, (err, resp) => {
          if (err) {
            console.log(err);
            return;
          }
      
          console.log(resp);
        });
      
      });
      

      然后您需要获取线程列表(每个请求(页面)100 个)。对于每个线程对象,您需要为完整线程调用 get 方法。使用 Gmail API 授权作为您要从中获取电子邮件的用户时。在请求中作为userId 使用值'me'

      【讨论】:

        猜你喜欢
        • 2011-08-16
        • 2020-01-21
        • 2014-12-06
        • 2018-12-29
        • 2014-05-15
        • 2019-02-20
        • 1970-01-01
        • 2022-07-11
        相关资源
        最近更新 更多