Home > Uncategorized > Sending attachments #base64 encoded with #SMTPJS

Sending attachments #base64 encoded with #SMTPJS


SmtpJS is a client-side javascript library, that allows you send Email from webpages without any server-side code hosted on your server.

It’s really simple just to send a simple email, but imagine, you wanted to send an attachment also, perhaps asking the user to upload their own attachment to be sent?

Here is a code example, that allows a user “upload” a file to be sent, and then sends the attachment as base64 data. I’ve omitted the secure token, from the example below – you can get one at SMTPJS.com

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="file" id="fileupload" onchange="uploadFileToServer()" />
function uploadFileToServer()
  var file = event.srcElement.files[0];
   var reader = new FileReader();
   reader.onload = function () {
       var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
           SecureToken : "********",
           To : 'info@destination.com',
           From : "you@source.com",
           Subject : "Send with base64 attachment",
           Body : "Sending file:" + file.name,
           Attachments : [
          		name : file.name,
          		data : dataUri
         message => alert(message)
   reader.onerror = function() {
       console.log('there are some problems');

What this does, is when the user selects a file, uploadFileToServer is triggered, this then passes a reference to the uploaded file to FileReader which then reads the contents of the file asynchronously, when the file reading is complete the “onload” event of the FileReader object is triggered. The file data is converted form a BLOB to base 64 using the BTOA method, and simple string concatenation forms this into the correct format for a DataUri. 

The base64 data, and the file name is then included in the Attachments array of the object passed to the Email.send function. Using the property “data” rather than “path”.

An alert box reporting “OK” indicates that everything has worked well.


Categories: Uncategorized
  1. Selva
    July 28, 2020 at 12:02 pm

    Invalid URI: The Uri string is too long.


  2. Jonas
    August 18, 2021 at 7:08 am

    Please help us to send attachment from our pc
    Not familliar what is dataUri, please enlighten us.


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: