简体   繁体   中英

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

I believe your goal as follows.

  • You want to add the custom headers of List-Unsubscribe and List-Unsubscribe-Post to the Gmail and send it using Google Apps Script.

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)
  • In this sample, List-Unsubscribe: sample1 and List-Unsubscribe-Post: sample2 are used as the sample values. Please modify this for your actual situation.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM