Reputation: 775
Forgive me if I have used the wrong terminology to describe my issue, please do correct me. I am developing in node and express. I want to be able to call nodemailer from anywhere in my app without re-creating the transporter. How do I do this, I had thought that I just needed to put this in app.js and then it would work. I am using mailgun-nodemailer.
app.js
var auth = {
auth: {
api_key: 'key-XXXXX',
domain: 'XXXXX.mailgun.org'
}
}
var mailgun = nodemailer.createTransport(mg(auth));
acontroller.js
mailgun.sendMail(mailOptions, function(err) {
req.flash('success', { msg: 'Success! Your password has been changed.' });
done(err);
});
Upvotes: 0
Views: 179
Reputation: 17999
Just remove the keyword var
and use global
instead so you mailgun
is global.
You'll need to load the file using require('app.js')
at the start of your application too. (before you need to call it, so basically when you start express I'd say)
var auth = {
auth: {
api_key: 'key-XXXXX',
domain: 'XXXXX.mailgun.org'
}
}
global.mailgun = nodemailer.createTransport(mg(auth));
Note that you also may use module.exports.mailgun = nodemailer.createTransport(mg(auth))
and then load it using
require('app.js').mailgun.sendMail(mailOptions, function(err) {
req.flash('success', { msg: 'Success! Your password has been changed.' });
done(err);
});
In that case I would advise you to rename the file app.js
to mailgun.js
, makes more sense.
So there are two way, either a global var or using the usual node.js require function, do as you want, we usually use the require
way, but if you don't want to be worried about paths then using a global var makes sense.
Upvotes: 2