问题
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:-
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.
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