Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created October 11, 2021 00:47
Show Gist options
  • Save tanaikech/187863d97d2b5e60938d8316574a2850 to your computer and use it in GitHub Desktop.
Save tanaikech/187863d97d2b5e60938d8316574a2850 to your computer and use it in GitHub Desktop.
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

@nicolasmozo
Copy link

Thank you!

@luffy-yu
Copy link

Thank you!

For anyone who is looking for the Python version. I used ChatGPT to translate it and found it works.

import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def convert_(to, email_from, name_from, subject, text_body, html_body):
    boundary = "boundaryboundary"

    msg = MIMEMultipart('alternative')
    msg['MIME-Version'] = '1.0'
    msg['To'] = to
    if name_from and email_from:
        msg['From'] = f'"{name_from}" <{email_from}>'
    msg['Subject'] = f'=?UTF-8?B?{base64.b64encode(subject.encode("utf-8")).decode()}?='
    msg['Content-Type'] = f'multipart/alternative; boundary={boundary}'

    # Plain text part
    text_part = MIMEText(text_body, 'plain', 'UTF-8')
    msg.attach(text_part)

    # HTML part
    html_part = MIMEText(html_body, 'html', 'UTF-8')
    msg.attach(html_part)

    raw_message = msg.as_string().encode('utf-8')
    encoded_message = base64.urlsafe_b64encode(raw_message).decode('utf-8')

    return encoded_message

# Please run this function.
def main():
    obj = {
        'to': '###',  # Please set the email for `to`.
        'email_from': '###',  # Please set the email for `from`.
        'name_from': 'sample name',
        'subject': 'Hello World 😃⭐',
        'text_body': 'sample text body 😃⭐',
        'html_body': '<p>Hello World 😃⭐</p>',
    }
    
    # Assuming the Python equivalent for Gmail.Users.Messages.send is used here.
    # You may need to adjust this part based on the library or API you are using.
    # Also, make sure to replace 'me' with the appropriate user identifier.
    send_message(convert_(**obj), 'me')

# Dummy function for sending the message, replace it with the actual implementation.
def send_message(raw_message, user_id):
    print(f"Sending message to {user_id}:\n{raw_message}")

if __name__ == "__main__":
    main()

@mfloreslucas
Copy link

Hi! I've just add some code lines that helps to send attachment pdf, it was weird but it worked for me, thank you for inspiring me! I wanted to add the signature from the user but I can't dedicate more hours to it

const convertttt_ = ({ to, emailFrom, nameFrom, subject, textBody, pdfBlob }) => {
  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/mixed; boundary=${boundary}`,
    ``,
    `--${boundary}`,
    `Content-Type: multipart/alternative; boundary=${boundary}-alt`,
    ``,
    `--${boundary}-alt`,
    `Content-Type: text/plain; charset=UTF-8`,
    `Content-Transfer-Encoding: base64`,
    ``,
    Utilities.base64Encode(textBody, Utilities.Charset.UTF_8),
    ``,
    `--${boundary}-alt--`,
    ``,
    `--${boundary}`,
    `Content-Type: application/pdf; name="${pdfBlob.getName()}"`,
    `Content-Disposition: attachment; filename="${pdfBlob.getName()}"`,
    `Content-Transfer-Encoding: base64`,
    ``,
    Utilities.base64Encode(pdfBlob.getBytes()),
    ``,
    `--${boundary}--`,
  ].join("\r\n");
  return Utilities.base64EncodeWebSafe(mailData);
};

// Please run this function.
function main() {
  var pdfFile = DriveApp.getFileById('### File ID in drive ###');
  var pdfBlob = pdfFile.getBlob();

  const obj = {
    to: "###", 
    emailFrom: "###", 
    nameFrom: "###",
    subject: "tuki🤩",
    textBody: sample text body 😃⭐,
    pdfBlob: pdfBlob 
  };
 
  Gmail.Users.Messages.send({ raw: convertttt_(obj) }, "me");
}

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