Send email using GMail API in Google Apps Script

2019-02-25 05:44发布

I have a raw email (tested on playground and working) and I want to send it with Google's Gmail API from Google Apps Script.

I can't find the right syntax for the request:

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);

What is wrong with my syntax?

2条回答
在下西门庆
2楼-- · 2019-02-25 05:55

I found the solution to my question:

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

jsonMessage is the whole message, not only the raw part!

查看更多
叛逆
3楼-- · 2019-02-25 06:10

In Google Apps Script, you can use the Advanced Gmail Service without needing to fuss with the Web API directly. Remember, the service must be 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;
}
查看更多
登录 后发表回答