If you need to send email from your application, there are many email providers to pick from (Mailgun, Sendgrid etc.).
But the advantage of using Gmail for your email transport is the almost zero technical setup to get it up and running.
Furthermore, it also lets you use your company email address in the sent-from and reply-to fields.
In this example we'll show you how to create a database trigger (codehook) that calls a JavaScript that sends email with the Gmail smtp transport.
Example
If you didn't know it already, restdb.io can trigger a JavaScript Codehook on a particular data event.
E.g.: the screen shot below shows our example trigger afterPOST(…)
.
This function is called on each POST to a database collection that we've called mailtrigger:
The JavaScript code for sending email:
// Codehooks for mailtrigger
function afterPOST(req, res){
log.debug("afterPOST",req.apikey);
var htmlmail = "<h1>Alert!</h1>A record was created in the database <p>Best regards Acme</p>";
var mailopt = {
transport: "Gmail", // use Gmail transport
to: req.body.email, // send to an email address from the database record
subject: "Trigger email from you database", // Email subject
html: htmlmail, // HTML formatted email message
company: "Acme Inc", // Email footer
sendername: "Acme support" // Email sendername, hides the email address
};
// send email with the API
sendMail(mailopt, function(maildata){
res.end();
});
}
Gmail settings
To use Google as SMTP transport you need to store your username and passord in a protected space, the database settings is perfect for this. In Development mode, navigate to the Settings tab (from the top level) and add the following JSON setting:
{
…
"restdb": {
"Gmail-service": {
"auth": {
"user": "<your Gmail email address>",
"pass": "<your Gmail password>"
}
}
}
}
You must also set up your Gmail account to allow SMTP connections. Navigate on your Gmail account to: My account / Sign-in & security / Connected apps & sites. Then click the setting to ON for allowing access from your database:
You're all set.
Creating new (POST) records in our collection now sends emails from the JavaScript trigger. The example result is shown in the screen shot below:
This blog post has shown how easy it is to get started with sending emails from your application.
Note: using the Gmail for transport is avaliable for paid plans.