Skip to content

Instantly share code, notes, and snippets.

@mfloreslucas
Last active February 28, 2024 00:28
Show Gist options
  • Save mfloreslucas/18c28ef0e6075de0710cce35464f1cd0 to your computer and use it in GitHub Desktop.
Save mfloreslucas/18c28ef0e6075de0710cce35464f1cd0 to your computer and use it in GitHub Desktop.
Gmail send via AppsScripts [emotes and attatchment file]

Sending Gmail with emotes and attachment file (PDF) Google Apps Scripts

  • This is a simple script for sending mails using dynamic messages or pdfs or mails. For example I've got this working with a Google Sheets file that is used as a database where are pdfs names and mails of people involved.
  • You can even do work this script in almost any Google Workspace software.
  • Credits for @tanaikench that inspired me a lot

Final Result

Code

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

Reference

  • I was very inspired by what this user did in this post I found, I used the same documentation he points out in his gist.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment