Wednesday, June 11, 2014

Send email use Node.js on BlueMix

There are many ways to send eamil use node.js.Today I will introduce three ways to send email.

1.Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES or even your own method) and is unicode friendly - You can use any characters you like.

The whole development is very easy.
a)Install Nodemailer
> npm install nodemailer
b)Write below code
var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
   service: "Gmail",
   auth: {
       user: "XXX@gmail.com",
       pass: "XXX"
   }
});

var mail = {
    from: "XXX@gmail.com",
    to: "XXX@gmail.com",
    subject: "Send Email Using Node.js",
    text: "Node.js New world for me",
    html: "<b>Node.js New world for me</b>"
}

smtpTransport.sendMail(mail, function(error, response){
    if(error){
        console.log(error);
    }else{
        console.log("Message sent: " + response.message);
    }

    smtpTransport.close();
});

c) In node.js enviroment run nodeemail.js,you will see the email has been sent.

d)You can install it from npm. Add a dependency to your package.json and run npm install
package.json contents:
...
"dependencies": {
   "nodemailer": "0.3.29"
},
...

2. Since first way we need to use smtp and also need authenciation,sometimes we don;t have smtp server provided,so we need to use 'sendmail module to handle it .The code is more easy.

sendmail = require('sendmail')();

sendmail({
    from: 'XXXX@gmail.com',
    to: 'XXX@cn.ibm.com',
    subject: 'test sendmail',
    type: 'text/html',
    content: '<h3>hello</h3><p>Hey guys</p>
  }, function(err, reply) {
    console.log(err && err.stack);
    console.dir(reply);
});
Also you can reference this open source code at github.
https://github.com/guileen/node-sendmail

3.Using SendGrid service,you can reference below link.
https://github.com/sendgrid/sendgrid-nodejs#usage

1 comment:

  1. You need to remove the `"SMTP",` from the example above to make it work with nodemailer v2.

    ReplyDelete