Home > Uncategorized > Sending a base64 encoded file using #SMTP.js

Sending a base64 encoded file using #SMTP.js

smtpjs

SMTPjs.com is a javascript library that allows you send email through Javascript. – You still need access to a outgoing mail (SMTP) server, but this makes life a little easier for your JS apps.

Today, we released v2.0.1 of the library, which has a few important fixes

  • The message body is no longer limited in size
  • There is now an optional callback parameter, that allows your code continue after the email is sent.
  • Attachments can be sent in base 64 format (dataURI) to the library.

Previous versions of the library will continue to be functional, but we recommend upgrading to the latest version.

Callback feature:

Depending on whether you use a stored token, or send your SMTP credentials with every request, then you use one of the two following blocks of code:

Email.send(“from@you.com”,
“to@them.com”,
“Subject”,
“Body”,
“smtp.server.com”,
“username”,
“password”,
function done(message) { alert(“sent”) }
);

or, when using stored credentials;

Email.send(“from@you.com”,
“to@them.com”,
“Subject”,
“Body”,
{
token: “your-token”,
callback:function done(message) { alert(“sent”) }
});

DataUri Attachments

Previously, in order to send an attachment with this script, then the file you needed to send needed to be already hosted online. This, may not be ideal, if you wanted your user to select a file from their device, or otherwise dynamically generate the file to be sent.

So, let’s imagine we want the user to select a file to be sent from their device, we add a form element as follows;

<input type=”file” id=”fileupload” onchange=”uploadFileToServer()” />

Then define the function uploadFileToServer as follows:

function uploadFileToServer() {
var file = event.srcElement.files[0];
console.log(file);
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function () {
var datauri = “data:” + file.type + “;base64,” + btoa(reader.result);
Email.sendWithAttachment(“from@you.com”,
“to@them.com”,
“Subject”,
“Body”,
“smtp.server.com”,
“username”,
“password”,,
datauri,
function done(message) { alert(“Message sent OK”) }
);
};
reader.onerror = function() {
console.log(‘there are some problems’);
};
}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: