The built-in email connectors enables applications to send email.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:

  1. $ lb datasource

With API Connect v5 developer toolkit:

  1. $ apic create --type datasource

When prompted, select Email as the connector. This creates an entry in datasources.json like this (for example):

server/datasources.json

  1. ...
  2. "myEmailDataSource": {
  3. "name": "myEmailDataSource",
  4. "connector": "mail"
  5. }
  6. ...

Configuring an email data source

Configure the email data source by editing /server/datasources.json (for example):

server/datasources.json

  1. {
  2. ...
  3. "myEmailDataSource": {
  4. "connector": "mail",
  5. "transports": [{
  6. "type": "smtp",
  7. "host": "smtp.private.com",
  8. "secure": false,
  9. "port": 587,
  10. "tls": {
  11. "rejectUnauthorized": false
  12. },
  13. "auth": {
  14. "user": "me@private.com",
  15. "pass": "password"
  16. }
  17. }]
  18. }
  19. ...
  20. }

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:

For GMail, configure your email data source as follows:

server/datasources.json

  1. ...
  2. "Email": {
  3. "name": "mail",
  4. "connector": "mail",
  5. "transports": [{
  6. "type": "SMTP",
  7. "host": "smtp.gmail.com",
  8. "secure": true,
  9. "port": 465,
  10. "auth": {
  11. "user": "name@gmail.com",
  12. "pass": "pass"
  13. }
  14. }]
  15. }
  16. ...

Connecting a model to the email data source

Then, connect models to the data source in /server/model-config.json as follows (for example):

server/model-config.json

  1. {
  2. ...
  3. "Email": {
  4. "dataSource": "myEmailDataSource"
  5. },
  6. ...
  7. }

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:

server/models/model.js

  1. module.exports = function(MyModel) {
  2. // send an email
  3. MyModel.sendEmail = function(cb) {
  4. MyModel.app.models.Email.send({
  5. to: 'foo@bar.com',
  6. from: 'you@gmail.com',
  7. subject: 'my subject',
  8. text: 'my text',
  9. html: 'my <em>html</em>'
  10. }, function(err, mail) {
  11. console.log('email sent!');
  12. cb(err);
  13. });
  14. }
  15. };

The default model definition file is common/models/email.json in the LoopBack repository.

Confirming email address

See Verifying email addresses.

Tags: connectors