【问题标题】:Send email using GMail API in Google Apps Script在 Google Apps 脚本中使用 GMail API 发送电子邮件
【发布时间】:2016-05-05 21:33:55
【问题描述】:

我有一封原始电子邮件(在 Playground 上测试并正常工作),我想通过 Google Apps 脚本使用 Google 的 Gmail API 发送它。

我找不到请求的正确语法:

var RequestUrl = "https://www.googleapis.com/gmail/v1/users/emailAccount/messages/send";

var RequestArguments = {
    muteHttpExceptions:true,
    headers: {Authorization: 'Bearer ' + token
             'GData-Version': '3.0',
             'Content-Type': "message/rfc822",
             },
    payload: {"raw":raw},
    method:"post"
  };    

var result = UrlFetchApp.fetch(RequestUrl,RequestArguments);

我的语法有什么问题?

【问题讨论】:

标签: google-apps-script google-api gmail sendmail urlfetch


【解决方案1】:

在 Google Apps Script 中,您可以使用 Advanced Gmail Service,而无需直接使用 Web API。请记住,服务必须是enabled before use

/**
 * Send a raw RFC 2822 formatted and base64url encoded email
 * using the Advanced Gmail service.
 *
 * From http://stackoverflow.com/a/35073785/1677912
 *
 * @param {String}  raw  RFC 2822 formatted and base64url encoded message
 *
 * @returns {String}     Message ID of the message (now in Sent Messages).
 */
function sendRawMessage( raw ) {
  var message = Gmail.newMessage();
  message.raw = raw;
  var sentMsg = Gmail.Users.Messages.send(message, 'me');
  return sentMsg.id;
}

【讨论】:

  • 是的,但我想从不是有效用户的帐户发送电子邮件。
  • 这是一个重要的细节,你不觉得吗?
  • @Mogsdad 有没有办法代表其他用户使用高级 API 执行此操作?即他们已经授权我的应用程序,我如何通过高级服务传递 oauth 令牌?
【解决方案2】:

我找到了问题的解决方案:

var RequestArguments = {
  headers: {Authorization: 'Bearer ' + token},
  method: "post",
  contentType: "application/json",
  payload: JSON.stringify(jsonMessage)
};

jsonMessage 是整个消息,而不仅仅是原始部分!

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 2012-07-25
    • 2017-04-14
    • 1970-01-01
    • 2021-11-21
    • 2020-02-06
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多