Search code examples
google-apps-scriptgmail-api

How to send the email from Google Apps Script using GMAIL API?


I am trying to automise sending of the Emails from my account using Gmail API in Google Apps Script.

Here is my code:

function email_checker() {
  var yourEmailAddress = "###@gmail.com";
  var myEmailAddress = "support@###.com";
  var subject = "testing mail";
  var forScope = GmailApp.getInboxUnreadCount();
  var htmlBody = '<html><body>' + '<h1>HI</h1>' + '</body></html>';

  var message = 'From: Me <' + myEmailAddress + '>\r\n' +
    'To: Me <' + myEmailAddress + '>\r\n' +
    'Subject: ' + subject + '\r\n' +
    'Content-Type: text/html; charset=utf-8\r\n' +
    'Content-Transfer-Encoding: quoted-printable\r\n\r\n' +
    htmlBody;

  var draftBody = Utilities.base64Encode(message);
  draftBody = draftBody.replace(/\//g, '_').replace(/\+/g, '-');

  var params = {
    method: "post",
    contentType: "application/json",
    headers: {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true,
    payload: JSON.stringify({
      "message": {
        "raw": draftBody
      }
    })
  };

  var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params);
  Logger.log(resp.getContentText());
}

I am getting the following error: Media type 'application/json' is not supported.

Can anyone please advise on what I am doing wrong?

Thank you.


Solution

  • I believe your goal and your current situation as follows.

    • You want to send an email using Gmail API with UrlFetchApp.
    • You have already done the settings for sending the email.
      • Gmail API is enabled.
      • The scopes for sending emails can be included.

    Modification points:

    • From your endtpoint, it is found that the media upload request is used.
    • In this case,
      • the request body is required to create with multipart/alternative.
      • It is not required to use the base64 encode with the web safe.
      • The content type is required to use message/rfc822.
      • The created request body can be directly used for payload.

    When above points are reflected to your script, it becomes as follows.

    Modified script:

    function email_checker() {
      var yourEmailAddress = "###@gmail.com";
      var myEmailAddress = "support@###.com";
      var subject = "testing mail";
      var forScope = GmailApp.getInboxUnreadCount();
      var htmlBody = '<html><body>' + '<h1>HI</h1>' + '</body></html>';
    
      var message = 'MIME-Version: 1.0\r\n' +
        'From: Me <' + myEmailAddress + '>\r\n' +
        'To: Me <' + myEmailAddress + '>\r\n' +
        'Subject: ' + subject + '\r\n' +
        'Content-type: multipart/alternative; boundary=boundaryboundary\r\n\r\n' +
        '--boundaryboundary\r\n' +
        'Content-type: text/html; charset=UTF-8\r\n' +
        'Content-Transfer-Encoding: quoted-printable\r\n\r\n' +
        htmlBody + "\r\n\r\n" +
        '--boundaryboundary--';
    
      var params = {
        method: "post",
        contentType: "message/rfc822",
        headers: {
          "Authorization": "Bearer " + ScriptApp.getOAuthToken()
        },
        muteHttpExceptions: true,
        payload: message
      };
    
      var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params);
      Logger.log(resp.getContentText());
    }
    

    Note:

    • If you want to use the endpoint of POST https://gmail.googleapis.com/gmail/v1/users/{userId}/messages/send, please modify your script as follows.

      • From

          var params = {
            method: "post",
            contentType: "application/json",
            headers: {
              "Authorization": "Bearer " + ScriptApp.getOAuthToken()
            },
            muteHttpExceptions: true,
            payload: JSON.stringify({
              "message": {
                "raw": draftBody
              }
            })
          };
        
          var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send", params);
          Logger.log(resp.getContentText());
        
      • To

          var params = {
            method: "post",
            contentType: "application/json",
            headers: {
              "Authorization": "Bearer " + ScriptApp.getOAuthToken()
            },
            muteHttpExceptions: true,
            payload: JSON.stringify({"raw": draftBody})
          };
        
          var resp = UrlFetchApp.fetch("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", params);
          Logger.log(resp.getContentText());
        
      • In this case, var draftBody = Utilities.base64Encode(message); draftBody = draftBody.replace(/\//g, '_').replace(/\+/g, '-'); can be also modified to var draftBody = Utilities.base64EncodeWebSafe(message);.

    Reference: