Node.js Express Tutorial to Send Email Messages With Attachments Using NodeMailer Full Project

Node.js Express Tutorial to Send Email Messages With Attachments Using NodeMailer Full Project

Welcome folks today in this tutorial we will be discussing that how to send messages with attachments using node.js express and the nodemailer library from scratch. Let’s get started. You can see the detailed explanation video below to fully understand the blog.

 

 

Screenshots

 

 

Requirements

 

npm i express

 

npm i body-parser

 

npm i nodemailer

 

npm i multer

 

npm i --save-dev nodemon

 

Express : Express will be our server on which our application will be running at port 5000

body-parser: body parser is required to get the values out of the form that you submit from your html

nodemailer : It is the node library for sending messages with attachments very easily

multer : Multer is the dependecy to upload images to node server

 

Source Code

 

App.js

 

var nodemailer = require('nodemailer');
const express = require('express')
const bodyParser = require('body-parser');
const fs = require('fs')
const multer = require('multer')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'))
app.use(bodyParser.json())

var to;
var subject;
var body;
var path

var Storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, "./images");
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
    }
});

var upload = multer({
    storage: Storage
}).single("image"); //Field name and max count

app.get('/',(req,res) => {
    res.sendFile(__dirname + '/index.html')
})

app.post('/sendemail',(req,res) => {
    upload(req,res,function(err){
        if(err){
            console.log(err)
            return res.end("Something went wrong!");
        }else{
            to = req.body.to
            subject = req.body.subject
            body = req.body.subject
            path = req.file.path
            console.log(to)
            console.log(subject)
            console.log(body)
            console.log(req.file)
            console.log(req.files)
            var transporter = nodemailer.createTransport({
                service: 'gmail',
                auth: {
                  user: '######INSERTYOUREMAILHERE#####',
                  pass: '####INSERTYOURPASSWORDHERE####'
                }
              });
              
              var mailOptions = {
                from: '######INSERTYOUREMAILHERE#########',
                to: to,
                subject:subject,
                text:body,
                attachments: [
                  {
                   path: path
                  }
               ]
              };
              
              transporter.sendMail(mailOptions, function(error, info){
                if (error) {
                  console.log(error);
                } else {
                  console.log('Email sent: ' + info.response);
                  fs.unlink(path,function(err){
                    if(err){
                        return res.end(err)
                    }else{
                        console.log("deleted")
                        return res.redirect('/result.html')
                    }
                  })
                }
              });
        }
    })
})

app.listen(5000,() => {
    console.log("App started on Port 5000")
})

 

See also  Build a HTML5 Mini Photoshop Image Editor in Browser Using Javascript Full Project For Beginners

index.html

 

<!DOCTYPE html>
<html>
  <head>
    <title>Node.js Send Email</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">
            <br>
              Node.js Send Email With Attachment
          </h1>
          <br>
          <form action="/sendemail" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <input class="form-control" type="email" name="to" required placeholder="To:">
            </div>
            <div class="form-group">
                <input type="text" class="form-control" name="subject" placeholder="Subject:" required id="">
            </div>
            <div class="form-group">
                <textarea required class="form-control" name="body" id="" cols="30" rows="10" placeholder="Body:"></textarea>
            </div>
            <label for="attachment">Attachment:</label>
            <div class="form-group">
                <input type="file" required class="form-control" name="image" id="">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-block btn-danger">
                    Send Message
                </button>
            </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>

 

See also  jsPDF-Autotable Example to Convert Multiple HTML5 Tables to PDF Document With CSS in Javascript Full Project For Beginners

result.html

 

<!DOCTYPE html>
<html>
  <head>
    <title>Currency Converter in Javascript</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">Email Was Sent</h1>
          <a class="text-center" href="/">Sent More Email</a>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>

 

Some Important Points

 

  1. Make a images folder inside your directory to store your uploaded images
  2. Make a public folder inside your directory to store your html files
  3. Turn on your less secure App access for your gmail account. If you wanna see how to do it read my article

 

DOWNLOAD SOURCE CODE

Leave a Reply