How do you send emails from Angular controllers on the Mean.js stack?

拥有回忆 提交于 2019-12-23 04:30:48

问题


I'm using the Mean.js stack and I'm having issues figuring out how to send emails using the nodemailer package from inside an AngularJS controller. I have the following code:

var mailOptions = {
    from: 'Hello <hello@email.com>',
    to: 'email@gmail.com',
    subject: 'email subject',
    text: 'email body',
    html: 'html body'
};

var smtpTransport = nodemailer.createTransport(config.mailer.options);
smtpTransport.sendMail(mailOptions, function(err) {
    if (!err) {
        res.send({
            message: 'Email has been sent'
        });
    }

    done(err);
});

But I receive the error ReferenceError: nodemailer is not defined. I've tried injecting the dependency into the controller using:

angular.module('offers').controller('OffersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Offers', 'nodemailer',
    function($scope, $stateParams, $location, Authentication, Offers, nodemailer) {
    ...

but I only get the error Unknown provider: nodemailerProvider. I've also added the dependency to app/config/express.js as so nodemailer = require('nodemailer'), but still no luck.

I see in the npm package nodemailer/src/nodemailer.js the following lines:

function Nodemailer(transporter) {
...

and

module.exports.createTransport = function(transporter)
...

so I would assume that I could access the package through a global Nodemailer object, as so: Nodemailer.createTransport(...), but that is undefined as well.

Thanks for your help!


回答1:


I think Nodemailer have to run on server side.

Just trigger the sending with a $http request from angular.

You can find an example here

If you're getting a reference error please check that you've installed nodemailer correctly with npm install nodemailer --save.




回答2:


In your code, you cannot inject nodemailer in an angular controller because it is not a service or a provider.

You have 2 options:-

  1. Assuming it is just available as a node package and you have already installed it, you can include the script in your html file from node_modules folder, and that way nodemailer will be available in your app as a global object. Personally, I won't use this approach, and take the 2nd approach.

  2. This is the preferred option - Create an http endpoint on your node server which does the mailing bit using nodemailer. Then send an http request to the end point to do what you want.




回答3:


I think Nodemailer have to run on server side.

Just trigger the sending with a $http request from angular.

You can find an example here

If you're getting a reference error please check that you've installed nodemailer correctly with npm install nodemailer --save.



来源:https://stackoverflow.com/questions/30682461/how-do-you-send-emails-from-angular-controllers-on-the-mean-js-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!