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

Sending attachments #base64 encoded with #SMTPJS

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

<html>
<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="file" id="fileupload" onchange="uploadFileToServer()" />
<script>
function uploadFileToServer()
{
  var file = event.srcElement.files[0];
   var reader = new FileReader();
   reader.readAsBinaryString(file);
   reader.onload = function () {
       var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
       Email.send({
           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
          	}]
       }).then(
         message => alert(message)
       );
   };
   reader.onerror = function() {
       console.log('there are some problems');
   };
}
</script>
</html>

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.

    Like

  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.

    Like

  3. Divyansh
    March 15, 2023 at 3:47 pm

    hey that was working 100%, I was searching for this from days. Thank you so much!

    Like

  1. No trackbacks yet.

Leave a comment