Alex Alex - 1 year ago 374
Javascript Question

GMAIL API for sending Email with attachment

i' m working on a javascript client able to read a CSV which contains an image url list.

I m able to read the csv by the means of jquery-csv and to draw each image in a html5 canvas.

The next step is to apply to each image a text layer and to send the image by email using gmail api.

So my diffifulty is to find an example showing me how to take a canvas and to attach it to an email using only javascript.

Do have i to build a json according to the multipart gmail guidelines and to send it as POST body as specified?

Can you send me some example?

Answer Source
// Get the canvas from the DOM and turn it into base64-encoded png data.
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL();

// The relevant data is after 'base64,'.
var pngData = dataUrl.split('base64,')[1];

// Put the data in a regular multipart message with some text.
var mail = [
  'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
  'MIME-Version: 1.0\r\n',
  'Subject: Subject Text\r\n\r\n',

  'Content-Type: text/plain; charset="UTF-8"\r\n',
  'MIME-Version: 1.0\r\n',
  'Content-Transfer-Encoding: 7bit\r\n\r\n',

  'The actual message text goes here\r\n\r\n',

  'Content-Type: image/png\r\n',
  'MIME-Version: 1.0\r\n',
  'Content-Transfer-Encoding: base64\r\n',
  'Content-Disposition: attachment; filename="example.png"\r\n\r\n',

   pngData, '\r\n\r\n',


// Send the mail!
  type: "POST",
  url: "",
  contentType: "message/rfc822",
  beforeSend: function(xhr, settings) {
    xhr.setRequestHeader('Authorization','Bearer {YOUR_API_KEY}');
  data: mail
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download