Use the Gmail API to Send Emails with Attachments

Published in: Gmail - Google Apps Script

This example shows how you can easily send email messages with file attachment using the Gmail API. The attachments can be stored in Google Drive and you need to specify the file IDs that are to included in the outgoing messages.

We begin by creating a MIME message that complies with RFC 2822 standard and call the Gmail API to sends the specified message to the recipients in the To, Cc, and Bcc headers. We use the /upload URI with the messages/send method for uploading the files with the message and the uploadType is set to media for uploading the files without any metadata.

The code is written in Google Apps Script but Google also offers Gmail API Client libraries for PHP, Python, JavaScript and NodeJS. If you wish to include images, upload them to a site like imgur and include them in the email’s HTML body using img tags.

// Written by Amit Agarwal
// Web:
// Email:

function sendEmailWithAttachments() {

    var attachments = ["File_ID_1", "File_ID_2"];

    var message = {
        to: {
            name: "Google Scripts",
            email: ""
        from: {
            name: "Amit Agarwal",
            email: ""
        body: {
            text: "Mr hänn is schon lang nümme g'she.",
            html: "Mr hänn is schon <b>lang nümme</b> g'she."
        subject: "ctrlq, tech à la carte",
        files: getAttachments_(attachments)

    // Compose Gmail message and send immediately


function callGmailAPI_(message) {

    var payload = createMimeMessage_(message);

    var response = UrlFetchApp.fetch(
        "", {
            method: "POST",
            headers: {
                "Authorization": "Bearer " + ScriptApp.getOAuthToken(),
                "Content-Type": "message/rfc822",
            muteHttpExceptions: true,
            payload: payload



// UTF-8 characters in names and subject
function encode_(subject) {
    var enc_subject = Utilities.base64Encode(subject, Utilities.Charset.UTF_8);
    return '=?utf-8?B?' + enc_subject + '?=';

// Insert file attachments from Google Drive
function getAttachments_(ids) {
    var att = [];
    for (var i in ids) {
        var file = DriveApp.getFileById(ids[i]);
            mimeType: file.getMimeType(),
            fileName: file.getName(),
            bytes: Utilities.base64Encode(file.getBlob().getBytes())
    return att;

// Create a MIME message that complies with RFC 2822
function createMimeMessage_(msg) {

    var nl = "\n";
    var boundary = "__ctrlq_dot_org__";

    var mimeBody = [

        "MIME-Version: 1.0",
        "To: " + encode_( + "<" + + ">",
        "From: " + encode_( + "<" + + ">",
        "Subject: " + encode_(msg.subject), // takes care of accented characters

        "Content-Type: multipart/alternative; boundary=" + boundary + nl,
        "--" + boundary,

        "Content-Type: text/plain; charset=UTF-8",
        "Content-Transfer-Encoding: base64" + nl,
        Utilities.base64Encode(msg.body.text, Utilities.Charset.UTF_8) + nl,
        "--" + boundary,

        "Content-Type: text/html; charset=UTF-8",
        "Content-Transfer-Encoding: base64" + nl,
        Utilities.base64Encode(msg.body.html, Utilities.Charset.UTF_8) + nl


    for (var i = 0; i < msg.files.length; i++) {

        var attachment = [
            "--" + boundary,
            "Content-Type: " + msg.files[i].mimeType + '; name="' + msg.files[i].fileName + '"',
            'Content-Disposition: attachment; filename="' + msg.files[i].fileName + '"',
            "Content-Transfer-Encoding: base64" + nl,



    mimeBody.push("--" + boundary + "--");

    return mimeBody.join(nl);

Published in: Gmail - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch