Search code examples
gmailgmail-api

How to send mail with attachment and message in JavaScript via Gmail API


I can send a attachment,But I can't send attachment and messages

when I add message to send,it is failed.

  function sendMessage(message, callback)
  {

    var email =
        "To: " + $('#compose-to').val() + "\r\n" +
        "Subject: " + $('#compose-subject').val() + "\r\n" +
        'Content-Transfer-Encoding: base64\r\n' +
        'Content-Type: text/html; charset="UTF-8"\r\n' +
        "" +
        message+
        "\r\n\r\n" +
        "--foo_bar_baz\r\n" +
        "Content-Type: image/png\r\n" +
        "MIME-Version: 1.0\r\n" +
        "Content-Disposition: attachment\r\n\r\n" +
        file_ + "\r\n\r\n";

    var sendRequest = gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': window.btoa(unescape(encodeURIComponent(email))).replace(/\+/g, '-').replace(/\//g, '_')
      }
    });

    return sendRequest.execute(callback);
  }

hope send mail with attachment and message in javascript by gmail api


Solution

  • Posting answer for documentation purposes.

    According to the file upload documentation, it was necessary for the Content-Type to be changed to multipart/mixed. Most files will need this setting since it is how adding attachments works in the Gmail API.