使用Google Apps脚本中的GMail API发送电子邮件

时间:2016-01-28 13:19:51

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

我有一封原始电子邮件(在游乐场和工作中测试过),我希望通过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);

我的语法有什么问题?

2 个答案:

答案 0 :(得分:2)

在Google Apps脚本中,您可以使用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;
}

答案 1 :(得分:2)

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

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

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