Directly From Client
Send an email using only JavaScript
in short:
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email
Like this -
function sendMail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': 'YOUR API KEY HERE',
'message': {
'from_email': '[email protected]',
'to': [
{
'email': '[email protected]',
'name': '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
});
}
https://medium.com/design-startups/b53319616782
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.
Indirect via Your Server - secure
To overcome the above vulnerability, you can modify your own server to send the email after session based authentication.
node.js - https://www.npmjs.org/package/node-mandrill
var mandrill = require('node-mandrill')('<your API Key>');
function sendEmail ( _name, _email, _subject, _message) {
mandrill('/messages/send', {
message: {
to: [{email: _email , name: _name}],
from_email: '[email protected]',
subject: _subject,
text: _message
}
}, function(error, response){
if (error) console.log( error );
else console.log(response);
});
}
// define your own email api which points to your server.
app.post( '/api/sendemail/', function(req, res){
var _name = req.body.name;
var _email = req.body.email;
var _subject = req.body.subject;
var _messsage = req.body.message;
//implement your spam protection or checks.
sendEmail ( _name, _email, _subject, _message );
});
and then use use $.ajax on client to call your email API.