Search code examples
node.jsloopbackjsnodemailerloopback

Loopback Email Connector not sending emails


I have a Loopback Application with a REST API.

I want to make a REST API Enpoint /Email/sendEmail which sends an email. I did this tutorial: https://loopback.io/doc/en/lb3/Email-connector.html, but it's not working for me somehow.

When I open https://localhost:3000/explorer , I can see the API Endpoint and I can press the button "Try it out". But then it just loads forever and after a while I get a Timeout error in the console.

File: datasource.json

{
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "siemens",
    "password": "",
    "name": "db",
    "user": "",
    "useNewUrlParser": true,
    "connector": "mongodb"
  },
  "email": {
    "name": "email",
    "connector": "mail",
    "transports": [{
      "type": "SMTP",
      "host": "smtp.gmail.com",
      "secure": true,
      "port": 465,
      "auth": {
        "user": "xbit.dany@gmail.com",
        "pass": "XXX"
      }
    }]
  }
}

File: model-config.json

"Email": {
    "dataSource": "email",
    "public": true
  }

File: email.js

module.exports = function(Email) {

  // send an email
  Email.sendEmail = function(cb) {
    console.log("Sending Email");
    Email.app.models.Email.send({
      to: 'siemens.dany@gmail.com',
      from: 'xbit.dany@gmail.com',
      subject: 'my subject',
      text: 'my text',
      html: 'my <em>html</em>'
    }, function(err, mail) {
      console.log('email sent!');
      cb(err);
    });
  }

  Email.remoteMethod(
    'sendEmail', {
      http: {
        path: '/sendEmail',
        verb: 'get'
      },
      returns: {

      }
    }
  );

};

File: models/email.json

{
    "name": "Email",
    "base": "Model",
    "properties": {
      "to": {"type": "String", "required": true},
      "from": {"type": "String", "required": true},
      "subject": {"type": "String", "required": true},
      "text": {"type": "String"},
      "html": {"type": "String"}
    }
}

Solution

  • The mail is now working. This is the code of email.js

    module.exports = function(emailDS) {
    
      // send an email
      emailDS.sendEmail = function(cb) {
        console.log("Sending Email");
    
        emailDS.app.models.Email.send({
          to: 'siemens.dany@gmail.com',
          from: 'xbit.dany@gmail.com',
          subject: 'my subject',
          html: 'my <em>html</em>'
        }, function(err, mail) {
          console.log("Mail: " + mail);
          console.log("Error: " + err);
          cb(null, mail);
        });
      }
    
      emailDS.remoteMethod(
        'sendEmail', {
          http: {
            path: '/sendEmail',
            verb: 'get'
          },
          returns: {
            arg: 'Status', type:'string'
          }
        }
      );
    
    };