Test HTTP Requests Tools Blog PHP Quiz API Log In With Github
Test HTTP Requests Tools Blog PHP Quiz API Log In With Github
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

Send emails with attachments using JavaScript

Daniel Gheorghe Difficulty: 15 / 50 Tweet
mail-with-javascript

Update: October 16th, 2016

My Mandrill API Key stopped working a few months ago, when they became a paid service @MailChimp (source). I have updated the code below and you should be able to use the demo now.

Even so, if Mandrill ever dies again, you can use any other service with the same logic described in this tutorial. The JavaScript logic remains exactly the same.

Update: December 22nd, 2015

Reading file data as dataUrl ... using filereader.readAsDataURL(file) causes broken attachments. I updated the code to use arrayBuffer and then convert that to base64 and all my tests with various file types worked. I updated the code below and the gist.

Original article from November 2015

A few days ago a client asked me if I could send out emails with attachments using client side code only. At first I laughed, asking myself why would anyone want to do that, but then I thought: "Who cares! Whatever the client wants!". In the end I did find out that this was caused because of the hosting environment that he used which didn't allow any type of server-side code to be executed (Sooooo weird!).

Anyway, because I am a Mandrill subscriber myself I decided to use their API to meet this unusual request. I needed to be able to add attachments, so the challenge was to read the contents of the uploaded file and send it as an encoded string to the API end-point at Mandrill as mentioned in their documentation. I achieved this through the FileReader API. Once I had that, I just assembled the request pay-load and sent it to Mandrill who in turn did all the hard work.

Below is the JavaScript code and I've also assembled a demo that outputs the response from Mandrill. I also uploaded a gist for convenience.

Don't bother using the same API key, it doesn't actually send out any emails.

    
        <script>
            var MandrillApi = {};
            MandrillApi.key = 'VoyzlheXND-Imx1UoGqtqw';
            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": "[email protected]", //add your from field here
                    "from_name": "CodePunker", //add your from name here
                    "to": [
                        {
                            "email": "[email protected]", //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();
            });
        </script>