Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send emails with attachments using the Mandrill API and JavaScript
var MandrillApi = {};
MandrillApi.key = 'KpRWQQv1hIhKhkS1i7Az2A';
MandrillApi.theform = $('#demo');
MandrillApi.arrayBufferToProperBase64 = function(buffer) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
};
MandrillApi.processFile = function() {
'use strict';
var theform = this.theform;
console.log(theform.find('input[type=file]'));
var thefile = theform.find('input[type=file]')[0].files[0];
var reader = new FileReader();
var thefiledata;
var self = this;
thefiledata = reader.readAsArrayBuffer(thefile);
reader.onloadend = function () {
/*PUSH FILE CONTENTS TO THE CALLBACK THAT SENDS THE MESSAGE*/
MandrillApi.sendEmail(self.arrayBufferToProperBase64(reader.result));
};
};
MandrillApi.sendEmail = function(fileData) {
'use strict';
var theApiData = {};
var thefile = this.theform.find('input[type=file]')[0].files[0];
var thefiledata = fileData;
theApiData.key = this.key;
theApiData.message = {
"html": $("#html").val(), //add your html here
"text": "", //add your text here
"subject": "This is a demo email", //add your subject here
"from_email": "info@codepunker.com", //add your from field here
"from_name": "CodePunker", //add your from name here
"to": [
{
"email": "anotheremail@codepunker.com", //add your to email addr here
"name": "",
"type": "to" //bcc or cc
}
],
"attachments": [
{
"type": thefile.type, //file type
"name": thefile.name, //file name
"content": thefiledata //file contents
}
],
};
//now send the request
$.ajax({
url: "https://mandrillapp.com/api/1.0/messages/send.json",
type: 'POST',
data: theApiData,
async: false,
}).done(function (data) {
var r = JSON.stringify(data);
$("#output").val(JSON.stringify(r), null, '\t');
});
};
//init
MandrillApi.theform.submit(function(e){
e.preventDefault();
MandrillApi.processFile();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment