Tute 10: Sending mail by nodemailer in expressjs - ariffira/node-basic GitHub Wiki

Sending mail by nodemailer

install: npm install nodemailer --save

include:

//nodemailer includes
const nodemailer = require("nodemailer");

Set up youir transport service who will carry your email. Here i am using gmail.

Step 01: create a route for contact form view

// contact form routes
app.get('/contact', (req, res) => {
   //res.send('heloo contact')
   res.render('contactForm');
});

set view as:

<div class="container">
    <div class="col-md-6">
      <form action="/sendEmail" method="post">
        <div class="form-group">
          <label>Your Email</label>
          <input type="email" class="form-control" name="emailFrom" placeholder="[email protected]">
        </div>
        <div class="form-group">
          <label>Subject:</label>
          <input type="text" class="form-control" name="emailSubject">
        </div>
        <div class="form-group">
          <label>Message</label>
          <textarea class="form-control" name="emailBody" rows="3"></textarea>
        </div>
        <div class="form-group">
          <button class="btn btn-success" type="submit">Send Email</button>
        </div>
      </form>
    </div>
</div>

Step 02: Setup routes for email which will send email

// send email to contact
app.post('/sendEmail', (req, res) => {
   //here we will setup all config for email and then send email
});

Step 03: Setup email transporter/postoffice in /sendEmail route where you send your email/mail

   // setup email tranporter(it is postman)
   let transporter = nodemailer.createTransport({
     service: 'gmail', //like deutsche post
     auth: {
       user: '[email protected]', //your email
       pass: '@r1ful2018' //your password of email address
     }
   });
```

**Step 04: configure email details (your postman who will send it for you)**

```
// configure email details
   const mailOptions = {
      from: req.body.emailFrom, //sender address
      to: '[email protected]', //receiver address
      subject: req.body.emailSubject, // email subject
      html: "<h1 style='color: blue'>" + req.body.emailBody + "</h1>" //email body or messages
   };
```

**Step 05: Now finally send email using tranporter and mailoptions**

```
// send email now
   transporter.sendMail(mailOptions, (err, info)=> {
     if(err) {
       console.log(err);
     } else {
       console.log(info);
       res.send('email send successfully......!');
     }
   });
```

Seems cool. Please try to update like:

* make your email body content nice using your own template and send it to user
* add footer and header to the email
* send email from server to all its clients


⚠️ **GitHub.com Fallback** ⚠️