Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create draft mail using Google apps script

I want to know if it's possible to create draft mail using Google Apps script. And if yes, how is it possible ?

Regards, Sebastien

like image 491
Seb P Avatar asked Jul 15 '13 17:07

Seb P


People also ask

Can I generate an email from Google Sheets?

There are two ways to send email from Google Sheets. You can either use a Google provided library or use a third party email service provider like MailChimp or SendGrid. Google provides two Apps Script libraries ( MailApp and GmailApp ) that make it very easy to send emails from Sheets.


1 Answers

At this point in time, there is no way to create a new message that appears in your Drafts folder. This functionality has been requested previously - see Issue 985. If you are interested in receiving any updates, visit and star the issue.

EDIT: While still not natively supported in Google Apps Script, you can create drafts by using the GMail API, using getOAuthToken() to authenticate (introduced Feb 2014). Drafts support was added to the API in June 2014, and an example of its use from GAS is shown in comment 29 of the above issue. Code reproduced here for convenience:

function createDraft() {

  var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope

  var raw = 
      'Subject: testing Draft\n' + 
      //'To: [email protected]\n' +
      'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\n' +
      'testing Draft msg\n' + 
      '--1234567890123456789012345678--\n';

  var draftBody = Utilities.base64Encode(raw);

  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://www.googleapis.com/gmail/v1/users/me/drafts", params);
  Logger.log(resp.getContentText());
  /*
   * sample resp: {
   *   "id": "r3322255254535847929",
   *   "message": {
   *     "id": "146d6ec68eb36de8",
   *     "threadId": "146d6ec68eb36de8",
   *     "labelIds": [ "DRAFT" ]
   *   }
   * }
   */
}
like image 191
Mogsdad Avatar answered Nov 07 '22 03:11

Mogsdad