javascriptgoogle-apps-scriptgoogle-sheetsgmailemoji

How to use Emoji in email subject using Google Apps Script?


I am trying to send out an email using Google Apps Script.

// try 1
const subject = 'Hello World 😃';

// try 2
const subject = 'Hello World ' + String.fromCodePoint('0x1F600');

GmailApp.sendEmail(
  'abc@gmail.com', subject, '',
  {htmlBody: '<p>Hello World 😃</p>', name: 'ABC'}
);

When I use a ⭐, it works perfectly in both subject and HTML body. However, when I use 😀, it shows black diamonds with question marks in both subject and HTML body.

I have also checked How to insert an emoji into an email sent with GmailApp? but it only showcases how to use it in the body of the email, not the subject.

I have tried using MailApp and it worked but I don't want to use it for some reasons.

Any idea on how to solve this?


Solution

  • I believe your goal as follows.

    Modification points:

    When above points are reflected to the script, it becomes as follows.

    Sample script:

    Before you use this script, please enable Gmail API at Advanced Google services. And, please set the variables in the function main() and run the function main().

    function convert(toEmail, fromEmail, name, subject, textBody, htmlBody) {
      const boundary = "boundaryboundary";
      const mailData = [
        `MIME-Version: 1.0`,
        `To: ${toEmail}`,
        `From: "${name}" <${fromEmail}>`,
        `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 toEmail = "###"; // Please set the email for `to`.
      const fromEmail = "###"; // Please set the email for `from`.
      const name = "ABC";
      const subject = "Hello World ・";
      const textBody = "sample text body ・";
      const htmlBody = "<p>Hello World ・</p>";
      var raw = convert(toEmail, fromEmail, name, subject, textBody, htmlBody);
      Gmail.Users.Messages.send({raw: raw}, "me");
    }
    

    Note:

    References: