Breaking

how to send email in nodejs using nodemailer NPM module.


In the code snip­pets that fol­low, we will go through each of the above steps.

STEP 1: Install the node­mailer package.

npm install nodemailer

Once you are done with this arti­cle, you should prob­a­bly learn more about node­mailer library from here.
.
STEP 2: Cre­at­ing a trans­port object in your route handler.

var nodemailer = require('nodemailer');

var router = express.Router();

app.use('/sayHello', router);

router.post('/', handleSayHello); // handle the route at example.com/sayhi

function handleSayHello(req, res) {
    // Not the movie transporter!
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'example@gmail.com', // Your email id
            pass: 'password' // Your password
        }
    });
    ...
    ...
    ...
}


STEP 3: Pre­pare some plain­text or HTML con­tent to be sent in the body. I am going to sim­ply use some text.

var text = 'Hello world from \n\n' + req.body.name;

STEP 4: Cre­ate a sim­ple JSON object with the nec­es­sary val­ues for send­ing the email.

var mailOptions = {
    from: 'example@gmail.com>', // sender address
    to: 'receiver@destination.com', // list of receivers
    subject: 'Email Example', // Subject line
    text: text //, // plaintext body
    // html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};

STEP 5: Your moment of glory! — Actu­ally send the email and han­dle the response.

transporter.sendMail(mailOptions, function(error, info){
    if(error){
        console.log(error);
        res.json({yo: 'error'});
    }else{
        console.log('Message sent: ' + info.response);
        res.json({yo: info.response});
    };
});

And thats pretty much all there is to it! It was quite sim­ple, wasn’nt it?

No comments:

Powered by Blogger.