Send an email using only JavaScript

No server-side languages involved.

I recently ran into the need of sending an email without any server-side technology. Luckily, this is a piece of cake with the awesome Mandrill App. (Disclaimer: I know nothing about Mandrill except for the fact that the first 12,000 emails per month are free.)

Here’s the skinny:

1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email

Step 1: Get an API key

Sign up for Mandrill. When you’re done, click on Get API Keys:

Select Get API Keys

On the next screen, press +Add API Key and copy your key:

Copy your API key

Step 2: Load jQuery

If you don’t use jQuery, write your own AJAX call or use whatever library you prefer.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Step 3: Use the $.ajax function to send an email

Make sure you’re using POST to submit your data.

$.ajax({
type: “POST”,
url: “https://mandrillapp.com/api/1.0/messages/send.json”,
data: {
‘key’: ‘YOUR API KEY HERE’,
‘message’: {
‘from_email’: ‘YOUR@EMAIL.HERE’,
‘to’: [
{
‘email’: ‘RECIPIENT_NO_1@EMAIL.HERE’,
‘name’: ‘RECIPIENT NAME (OPTIONAL)’,
‘type’: ‘to’
},
{
‘email’: ‘RECIPIENT_NO_2@EMAIL.HERE’,
‘name’: ‘ANOTHER RECIPIENT NAME (OPTIONAL)’,
‘type’: ‘to’
}
],
‘autotext’: ‘true’,
‘subject’: ‘YOUR SUBJECT HERE!’,
‘html’: ‘YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!’
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});

Here is a list of all the parameters Messages API supports:

https://mandrillapp.com/api/docs/messages.html

Optional: Send email with the click of a button

You can run the code above with the click of a button:

$('#yourButtonId').click(function() {
$.ajax({
// ...
});
});

That’s it! You can now send email using only JavaScript!


Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.

Like what you read? Give Marius Craciunoiu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.