Search code examples
google-apps-scriptgmailgmail-api

Modify only the subject and send the draft


I know how to send a Gmail draft with:

var draft = GmailApp.getDrafts()[0]; 
var msg = draft.send();

and how to modify the draft with update:

draft.update("[email protected]", "current time", "The time hello")

But how to modify the subject only and not the content, not the attachments (if any), not the recipient?


Solution

    • You want to update only the subject of draft.
    • You don't want to modify the text body, HTML body and attachment files.
    • You want to achieve this using Google Apps Script.

    If my understanding is correct, how about this sample script? I think that there are several answers. So please think of this as just one of them.

    In this sample script, I used Class GmailApp and Gmail API. The flow of script is as follows.

    1. Retrieve raw data of draft as a text using Class GmailApp.
    2. Replace the subject of the raw data.
    3. Convert the text to base64 using Utilities.base64EncodeWebSafe().
    4. Update the draft using new raw data by Gmail API.

    By this flow, only subject can be updated.

    Before you run this script, please enable Gmail API at Advanced Google Services and API console.

    Enable Gmail API v1 at Advanced Google Services

    • On script editor
      • Resources -> Advanced Google Services
      • Turn on Gmail API v1

    Enable Gmail API at API console

    • On script editor
      • Resources -> Cloud Platform project
      • View API console
      • At Getting started, click "Explore and enable APIs".
      • At left side, click Library.
      • At Search for APIs & services, input "Gmail". And click Gmail API.
      • Click Enable button.
      • If API has already been enabled, please don't turn off.

    Sample script:

    function updateDraftmail() {
      var newSubject = "new subject"; // Please set new subject.
      var userId = "me"; // Please set userId.
      var draft = GmailApp.getDrafts()[0]; // Retrieve a draft.
    
      var raw = draft.getMessage().getRawContent();
      var newRaw = raw.replace(/Subject: \w.+/, "Subject: " + newSubject);
      var newRawB64 = Utilities.base64EncodeWebSafe(newRaw, Utilities.Charset.UTF_8);
      Gmail.Users.Drafts.update({message: {raw: newRawB64}}, userId, draft.getId());
    }
    

    References :

    If I misunderstood your question and this was not what you want, I apologize.