如何使用谷歌应用程序脚本发送草稿电子邮件

Sim*_*dro 7 gmail google-apps-script gmail-api

我正在使用谷歌应用程序脚本,并希望创建一个脚本,从草稿中提取邮件,如果标签为"明天发送",则发送它们.查找带有特定标签的草稿非常简单:

 var threads = GmailApp.search('in:draft label:send-tomorrow');
Run Code Online (Sandbox Code Playgroud)

但是我没有看到用于发送消息的API!我看到的唯一选择是: - 打开消息 - 提取正文/附件/ title/from/to/cc/bcc - 发送带有上述参数的新消息 - 销毁之前的草稿

这看起来很烦人,我不确定它是否适用于嵌入式图像,多个附件等...

任何提示?

Mog*_*dad 10

我看到的唯一选择是: - 打开消息 - 提取正文/附件/ title/from/to/cc/bcc - 发送带有上述参数的新消息 - 销毁之前的草稿

这是Amit Agarawal撰写的这篇博客的主题.他的脚本完全符合您的描述,但不处理内联图像.对于那些,您可以调整本文中的代码.

但是你是对的 - 如果你不能发送愚蠢的东西,甚至有一条草稿信息的重点是什么?!

我们可以使用GMail API Users.drafts:从Google Apps脚本发送以发送草稿.以下独立脚本执行此操作,并处理必要的授权.

脚本

完整的脚本可以在这个要点中找到.

/*
 * Send all drafts labeled "send-tomorrow".
 */
function sendDayOldDrafts() {
  var threads = GmailApp.search('in:draft label:send-tomorrow');

  for (var i=0; i<threads.length; i++) {
    var msgId = threads[0].getMessages()[0].getId();
    sendDraftMsg( msgId );
  }
}


/**
 * Sends a draft message that matches the given message ID.
 * Throws if unsuccessful.
 * See https://developers.google.com/gmail/api/v1/reference/users/drafts/send.
 *
 * @param {String}     messageId   Immutable Gmail Message ID to send
 *
 * @returns {Object}               Response object if successful, see
 *                                 https://developers.google.com/gmail/api/v1/reference/users/drafts/send#response
 */
function sendDraftMsg( msgId ) {
  // Get draft message.
  var draftMsg = getDraftMsg(msgId,"json");
  if (!getDraftMsg(msgId)) throw new Error( "Unable to get draft with msgId '"+msgId+"'" );

  // see https://developers.google.com/gmail/api/v1/reference/users/drafts/send
  var url = 'https://www.googleapis.com/gmail/v1/users/me/drafts/send'
  var headers = {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
  };
  var params = {
    method: "post",
    contentType: "application/json",
    headers: headers,
    muteHttpExceptions: true,
    payload: JSON.stringify(draftMsg)
  };
  var check = UrlFetchApp.getRequest(url, params)
  var response = UrlFetchApp.fetch(url, params);

  var result = response.getResponseCode();
  if (result == '200') {  // OK
    return JSON.parse(response.getContentText());
  }
  else {
    // This is only needed when muteHttpExceptions == true
    var err = JSON.parse(response.getContentText());
    throw new Error( 'Error (' + result + ") " + err.error.message );
  }
}


/**
 * Gets the current user's draft messages.
 * Throws if unsuccessful.
 * See https://developers.google.com/gmail/api/v1/reference/users/drafts/list.
 *
 * @returns {Object[]}             If successful, returns an array of 
 *                                 Users.drafts resources.
 */
function getDrafts() {
  var url = 'https://www.googleapis.com/gmail/v1/users/me/drafts';
  var headers = {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
  };
  var params = {
    headers: headers,
    muteHttpExceptions: true
  };
  var check = UrlFetchApp.getRequest(url, params)
  var response = UrlFetchApp.fetch(url, params);

  var result = response.getResponseCode();
  if (result == '200') {  // OK
    return JSON.parse(response.getContentText()).drafts;
  }
  else {
    // This is only needed when muteHttpExceptions == true
    var error = JSON.parse(response.getContentText());
    throw new Error( 'Error (' + result + ") " + error.message );
  }
}

/**
 * Gets the draft message ID that corresponds to a given Gmail Message ID.
 *
 * @param {String}     messageId   Immutable Gmail Message ID to search for
 *
 * @returns {String}               Immutable Gmail Draft ID, or null if not found
 */
function getDraftId( messageId ) {
  if (messageId) {
    var drafts = getDrafts();

    for (var i=0; i<drafts.length; i++) {
      if (drafts[i].message.id === messageId) {
        return drafts[i].id;
      }
    }
  }

  // Didn't find the requested message
  return null;
}


/**
 * Gets the draft message content that corresponds to a given Gmail Message ID.
 * Throws if unsuccessful.
 * See https://developers.google.com/gmail/api/v1/reference/users/drafts/get.
 *
 * @param {String}     messageId   Immutable Gmail Message ID to search for
 * @param {String}     optFormat   Optional format; "object" (default) or "json"
 *
 * @returns {Object or String}     If successful, returns a Users.drafts resource.
 */
function getDraftMsg( messageId, optFormat ) {
  var draftId = getDraftId( messageId );

  var url = 'https://www.googleapis.com/gmail/v1/users/me/drafts'+"/"+draftId;
  var headers = {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
  };
  var params = {
    headers: headers,
    muteHttpExceptions: true
  };
  var check = UrlFetchApp.getRequest(url, params)
  var response = UrlFetchApp.fetch(url, params);

  var result = response.getResponseCode();
  if (result == '200') {  // OK
    if (optFormat && optFormat == "JSON") {
      return response.getContentText();
    }
    else {
      return JSON.parse(response.getContentText());
    }
  }
  else {
    // This is only needed when muteHttpExceptions == true
    var error = JSON.parse(response.getContentText());
    throw new Error( 'Error (' + result + ") " + error.message );
  }
}
Run Code Online (Sandbox Code Playgroud)

授权

要使用Google的API,我们需要为当前用户提供OAuth2令牌 - 就像我们为高级服务所做的那样.这是使用完成的ScriptApp.getOAuthToken().

将代码复制到您自己的脚本后,打开资源 - >高级Google服务,打开Goog​​le Developers Console的链接,然后为您的项目启用Gmail API.

只要脚本包含至少一个需要用户权限的GMailApp方法,就会为OAuthToken正确设置身份验证范围.在这个例子中,这是通过照顾GmailApp.search()sendDayOldDrafts(); 但是对于保险,您可以使用API​​直接在函数中包含不可访问的函数调用.