Here is a recipe to add a new module into Node.js. In this case, we'll use Nodemailer, a powerful and highly customizable API e-mail engine. We chose this module because we wanted to actually have the script do something interesting and not just spit out another onscreen print command. At the end of this recipe, you will be able to run a script that sends an e-mail to your inbox.
Open up LXTerminal. Alternatively, open up the Cloud9 IDE in the manner described in the previous section.
Create a directory for your projects using the following command:
$ mkdir projects
Perform the following steps after creating a directory for your project:
emailer
directory using the following command:$ cd projects $ mkdir emailer
$ cd emailer
$ npm init
You will see a series of prompts that you can fill out; you can skip them by hitting the return (Enter) key on your keyboard.
What you will do with these prompts and inputs is create the metadata to populate a file called package.json
. This file's purpose is to give information to npm
, which allows it to identify the project as well as handle the project's dependencies.
nodemailer
:$ sudo npm install nodemailer --save
nano
window with a new filename, as described here:$ cd node_modules/nodemailer $ sudo nano nodemailer-test.js
nano
window://This code has been modified from the nodemailer github example. var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: '[email protected]', pass: 'user_password' } }); // setup e-mail data with unicode symbols var mailOptions = { // sender address from: 'Ground Control <[email protected]>', // list of receivers to: 'sender_name1@some_domain.com, [email protected]', // Subject line subject: 'This is Ground Control to Major Tom', // plaintext body text: 'Can you hear me, Major Tom?', // html body html: '<b>Can you hear me Major Tom?</b>' }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); });
The preceding code is a modification of nodemailer's GitHub example. Also note: if you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Nodemailer/blob/master/examples/nodemailer-test.js.
Finally, if you use Gmail for your account in this example and run into login errors, there are numerous troublehooting tips here: https://github.com/andris9/nodemailer-wellknown/issues/3.
nano
, and then type Y
for "yes".Then, press the return (Enter) key.
$ node nodemailer-test.js
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
52.15.59.163