如何使用谷歌应用程序脚本发送草稿电子邮件 [英] How to send a draft email using google apps script

查看:172
本文介绍了如何使用谷歌应用程序脚本发送草稿电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google应用程序脚本,并希望创建一个脚本,用于从草稿中提取邮件,并在标签为发送 - 明天时发送邮件。
使用特定标签查找草稿非常简单:

  var threads = GmailApp.search('in:draft label :发送-明天'); 

但是我没有看到API发送消息!
我看到的唯一选项是:
- 打开消息
- 从body / attachments / title / from / to / cc / bcc中提取消息
- 发送一条新消息以上参数
- 销毁以前的草稿



这看起来非常烦人,我不确定会对嵌入式图像,多重附件等有效。



任何提示?

解决方案


我看到的唯一选项是: - 打开消息 - 从body / attachments / title / from / to / cc / bcc中提取 - 使用上面的参数发送新消息 - 销毁以前的草稿
blockquote>

这是此博客的确切主题阿米特阿加拉瓦尔。他的脚本只是描述你的内容,但不处理内联图像。对于这些用户,您可以调整这篇文章

但是你说得对 - 如果你不能发送愚蠢的东西,即使有草稿信息也有什么意义?!



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

脚本



完整脚本为可在这份要求中找到。

/ *
*发送所有标有send-tomorrow的草稿。
* /
函数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);
}
}


/ **
*发送与给定消息ID相匹配的草稿消息。
*如果不成功则抛出。
*请参阅https://developers.google.com/gmail/api/v1/reference/users/drafts/send。
*
* @param {String} messageId不可变的Gmail消息ID发送
*
* @returns {Object}响应对象如果成功,请参阅
* https: //developers.google.com/gmail/api/v1/reference/users/drafts/send#response
* /
函数sendDraftMsg(msgId){
//获取草稿消息。
var draftMsg = getDraftMsg(msgId,json);
if(!getDraftMsg(msgId))抛出新的错误(无法获取msgId的草稿'+ msgId +');

//请参阅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 = {
授权:'Bearer'+ ScriptApp.getOAuthToken()
};
var params = {
method:post,
contentType:application / json,
headers:headers,
muteHttpExceptions:true,
有效载荷: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 {
//这只在muteHttpExceptions == true时才需要
var err = JSON.parse(response.getContentText());
抛出新错误('Error('+ result +)+ err.error.message);
}
}


/ **
*获取当前用户的草稿消息。
*如果不成功则抛出。
*请参阅https://developers.google.com/gmail/api/v1/reference/users/drafts/list。
*
* @returns {Object []}如果成功,则返回
* Users.drafts资源数组。
* /
函数getDrafts(){
var url ='https://www.googleapis.com/gmail/v1/users/me/drafts';
var headers = {
授权:'Bearer'+ ScriptApp.getOAuthToken()
};
var params = {
标题:标题,
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 {
//这仅仅在muteHttpExceptions == true时才需要
var error = JSON.parse(response.getContentText());
抛出新错误('Error('+ result +)+ error.message);
}
}

/ **
*获取与给定的Gmail消息ID相对应的草稿消息ID。
*
* @param {String} messageId不可变的Gmail邮件ID,用于搜索
*
* @returns {String}不变的Gmail草稿ID,如果未找到,则返回null
* /
函数getDraftId(messageId){
if(messageId){
var drafts = getDrafts();

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

//未找到请求的消息
return null;
}


/ **
*获取与给定的Gmail消息ID相对应的消息草稿内容。
*如果不成功则抛出。
*请参阅https://developers.google.com/gmail/api/v1/reference/users/drafts/get。
*
* @param {String} messageId不可变的Gmail消息ID,用于搜索
* @param {字符串} optFormat可选格式; object(默认)或json
*
* @returns {Object或String}如果成功,返回一个Users.drafts资源。
* /
函数getDraftMsg(messageId,optFormat){
var draftId = getDraftId(messageId);

var url ='https://www.googleapis.com/gmail/v1/users/me/drafts'+\"/\"+draftId;
var headers = {
授权:'Bearer'+ ScriptApp.getOAuthToken()
};
var params = {
标题:标题,
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 {
//只有当muteHttpExceptions == true时才需要这个变量
var error = JSON.parse(response.getContentText());
抛出新错误('Error('+ result +)+ error.message);




授权

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



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



只要脚本至少包含一个需要用户权限的GMailApp方法,就会为OAuthToken正确设置认证范围。在这个例子中,这是由 GmailApp.search() sendDayOldDrafts()中处理的。但为了保险,您可以直接在使用API​​的函数中包含不可访问的函数调用。


I am working with Google apps script and would like to create a script which picks up mail from the drafts and sends them if they have label "send-tomorrow". Finding drafts with a certain label is pretty simple:

 var threads = GmailApp.search('in:draft label:send-tomorrow');

However I don't see an API to send the message! The only option I see is to: - open the message - extract body/attachments/title/from/to/cc/bcc - send a new message with the above params - destroy the previous draft

which seems pretty annoying and I'm not sure would work well with embedded images, multiple attachments etc...

any hint?

解决方案

The only option I see is to: - open the message - extract body/attachments/title/from/to/cc/bcc - send a new message with the above params - destroy the previous draft

This is the exact topic of this blog by Amit Agarawal. His script does just what you describe, but doesn't handle inline images. For those, you can adapt the code from this article.

But you're right - what's the point of even having a draft message if you can't just send the stupid thing?!

We can use the GMail API Users.drafts: send from Google Apps Script to send a draft. The following stand-alone script does that, and handles the necessary authorization.

Script

The full script is available in this gist.

/*
 * 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 );
  }
}

Authorization

To use Google's APIs, we need to have an OAuth2 token for the current user - just as we do for Advanced Services. This is done using ScriptApp.getOAuthToken().

After copying the code to your own script, open Resources -> Advanced Google Services, open the link for the Google Developers Console, and enable the Gmail API for your project.

As long as the script contains at least one GMailApp method that requires user authority, the authentication scope will be set properly for the OAuthToken. In this example, that's taken care of by GmailApp.search() in sendDayOldDrafts(); but for insurance you could include a non-reachable function call directly in the functions using the API.

这篇关于如何使用谷歌应用程序脚本发送草稿电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆