Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created Oct 11, 2021
Embed
What would you like to do?
Sending Gmail with Title and Body Including Emoji using Google Apps Script

Sending Gmail with Title and Body Including Emoji using Google Apps Script

This is a sample script for sending Gmail with the title and body including Emoji using Google Apps Script.

Sample script

This sample script uses Gmail API. So please enable Gmail API at Advanced Google services. Ref

const convert_ = ({ to, emailFrom, nameFrom, subject, textBody, htmlBody }) => {
  const boundary = "boundaryboundary";
  const mailData = [
    `MIME-Version: 1.0`,
    `To: ${to}`,
    nameFrom && emailFrom ? `From: "${nameFrom}" <${emailFrom}>` : "",
    `Subject: =?UTF-8?B?${Utilities.base64Encode(
      subject,
      Utilities.Charset.UTF_8
    )}?=`,
    `Content-Type: multipart/alternative; boundary=${boundary}`,
    ``,
    `--${boundary}`,
    `Content-Type: text/plain; charset=UTF-8`,
    ``,
    textBody,
    ``,
    `--${boundary}`,
    `Content-Type: text/html; charset=UTF-8`,
    `Content-Transfer-Encoding: base64`,
    ``,
    Utilities.base64Encode(htmlBody, Utilities.Charset.UTF_8),
    ``,
    `--${boundary}--`,
  ].join("\r\n");
  return Utilities.base64EncodeWebSafe(mailData);
};

// Please run this function.
function main() {
  const obj = {
    to: "###", // Please set the email for `to`.
    emailFrom: "###", // Please set the email for `from`.
    nameFrom: "sample name",
    subject: "Hello World 😃⭐",
    textBody: "sample text body 😃⭐",
    htmlBody: "<p>Hello World 😃⭐</p>",
  };
  Gmail.Users.Messages.send({ raw: convert_(obj) }, "me");
}
  • In order to use Emoji in the subject, the subject value is converted to the base64 data. And, it is used as =?UTF-8?B?###?=. Ref
  • About the method for including Emoji to the email body, I have answered it at this thread of Stackoverflow.

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment