google-apps-scriptgmail-apiemail-headers

How can I supply email headers sending in Google MailApp?


How can I include email headers information using Google MailApp api?

I need to supply headers info such as List-Unsubscribe: or List-Unsubscribe-Post:.

The following is a code sample by Google Apps Script. It seems that there is no option to include such email header info. sendEmail(recipient, subject, body, options)

// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 
'my_document.html');
MailApp.sendEmail('mike@example.com', 'Attachment example', 'Two files are attached.', {
                   name: 'Automatic Emailer Script',
                   attachments: [file.getAs(MimeType.PDF), blob]
});

Solution

  • I believe your goal as follows.

    In this case, how about the following flow?

    1. Create a draft as a temporal.
      • In this case, the arguments of MailApp.sendEmail in your script are used.
    2. Add the custom headers.
    3. Delete Draft.
    4. Send the draft using Gmail API.

    When this flow is reflected to your script, it becomes as follows.

    Modified script:

    Before you use this script, please enable Gmail API at Advanced Google services.

    var obj = {"List-Unsubscribe": "sample1", "List-Unsubscribe-Post": "sample2"}; // Please set the custom headers.
    
    // 1. Create a draft as a temporal.
    var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
    var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html');
    var draft = GmailApp.createDraft('mike@example.com', 'Attachment example', 'Two files are attached.', {
      name: 'Automatic Emailer Script',
      attachments: [file.getAs(MimeType.PDF), blob]
    });
    
    // 2. Add the custom headers.
    var data = Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join("\n") + "\n" + draft.getMessage().getRawContent();
    
    // 3. Delete Draft.
    draft.deleteDraft();
    
    // 4. Send the draft using Gmail API.
    var res = Gmail.Users.Messages.send({raw: Utilities.base64EncodeWebSafe(data)}, "me");
    console.log(res)
    

    References: