Home > Uncategorized > Sending multiple attachments with #SMTPJS

Sending multiple attachments with #SMTPJS

smtpjs

UPDATE:

Check out the V3 version of the API for a much easier way to do this:

https://blog.dotnetframework.org/2018/12/07/smtpjs-now-supports-multiple-attachments-replyto-and-sender-name/

 

One of the limitations of SMTPJS.com is that you can only send one attachment, this blog post demonstrates a way of sending multiple attachments, by zipping them into one file. It also keeps the size of your email down also.

This uses the JSZip library, which I’ve loaded via the cloudflare CDN. Note the mime type used: application/x-zip-compressed this is important, so that SMTPJS will send the file as a attachment named file.zip, rather than the default file.txt

<html>
src="https://smtpjs.com/v2/smtp.js">
src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.js">
language="javascript">
function uploadFileToServer()
{
  var zip = new JSZip();
  var numberOfFiles = event.srcElement.files.length;
  var numberOfProcessedFiles = 0;
  for(var i=0; inumberOfFiles; i++)
  {
    (function(i){
     var file = event.srcElement.files[i];
     var reader = new FileReader();
     reader.readAsBinaryString(file);
     reader.onload = function () {
        numberOfProcessedFiles++;
        zip.file(file.name,btoa(reader.result), {base64: true} );
        if (numberOfProcessedFiles == numberOfFiles)
        {
          zip.generateAsync({type:"base64"})
          .then(function(content) {
            var datauri = "data:application/x-zip-compressed;base64," + content;
            Email.sendWithAttachment("YOUR@EMAIL.com",
                "THEIR@EMAIL.com",
                "This is the Subject ",
                "This is the Body - see file.zip attachment!",
                "****SMTP HOST****",
                "****SMTP USERNAME****",
                "****SMTP PASSWORD****",
                datauri,
                function done(message)
                {
                   alert("Message sent OK")
                }
              );
          });
        }
     };
     })(i);
  }
}

<input type="file" id="fileupload" onchange="uploadFileToServer()" multiple/>
</html>


 

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment