The email connector is built in to LoopBack, so you don’t need to install it.
Nodemailer: Where to Find Documentation
The email connector is essentially a LoopBack-integrated interface to the nodemailer library. This page gives a usage example; for full documentation of configuration options, refer to the nodemailer documention.
Creating an email data source
Create a new email data source with the data source generator:
$ lb datasource
With API Connect developer toolkit:
$ apic create --type datasource
When prompted, select Email as the connector. This creates an entry in datasources.json
like this (for example):
...
"myEmailDataSource": {
"name": "myEmailDataSource",
"connector": "mail"
}
...
Configuring an email data source
Configure the email data source by editing /server/datasources.json
(for example):
{
...
"myEmailDataSource": {
"connector": "mail",
"transports": [{
"type": "smtp",
"host": "smtp.private.com",
"secure": false,
"port": 587,
"tls": {
"rejectUnauthorized": false
},
"auth": {
"user": "me@private.com",
"pass": "password"
}
}]
}
...
}
More Configuration Options
For full documentation of configuration options, refer to the nodemailer documention.
Using GMail
Tip: With GMail, you may need to enable the “access for less secure apps” option. See:
- Nodemailer: Using GMail
- Nodemailer: Authentication for more information.
For GMail, configure your email data source as follows:
...
"Email": {
"name": "mail",
"connector": "mail",
"transports": [{
"type": "SMTP",
"host": "smtp.gmail.com",
"secure": true,
"port": 465,
"auth": {
"user": "name@gmail.com",
"pass": "pass"
}
}]
}
...
Connecting a model to the email data source
Then, connect models to the data source in /server/model-config.json
as follows (for example):
{
...
"Email": {
"dataSource": "myEmailDataSource"
},
...
}
Sending email messages
The following example illustrates how to send emails from an app. Add the following code to a file in the /models
directory:
module.exports = function(MyModel) {
// send an email
MyModel.sendEmail = function(cb) {
MyModel.app.models.Email.send({
to: 'foo@bar.com',
from: 'you@gmail.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
}
};
The default model definition file is common/models/email.json in the LoopBack repository.