Indirect via Your Server - Calling 3rd Party API - secure and recommended
Your server can call the 3rd Party API after proper authentication and authorization. The API Keys are not exposed to client.
node.js - https://www.npmjs.org/package/node-mandrill
const 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){
let _name = req.body.name;
let _email = req.body.email;
let _subject = req.body.subject;
let _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.
Directly From Client - Calling 3rd Party API - not recomended
Send an email using only JavaScript
in short:
- register for Mandrill to get an API key
- load jQuery
- 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.