How to send a email with attachment using node js

1. Start with new node js project.
npm init -y
2. install express, nodemon, dotenv and nodemailer
npm i express mongoose dotenv nodemailer
Now you have a package.json and package.lock.json file in your project root folder.
3. Now create a index.js file in project root folder.
4. Write code for listen backend server on localhost.
1  const express = require('express') 
2  const app = express()
3  const dotenv = require('dotenv').config()
4  
5  app.use(express.json())
6  
7  // Server
8  const port = process.env.PORT || 6060
9  
10  app.listen(port, () => {
11      console.log(`Server is listen on port ${port}`)
12  })
13  
14  // test 
15  app.get('/', (req, res) => {
16      res.json({ name: "Your Name" })
17  })
5. Now create a connection folder in project root folder and create a connect.js file under connection folder.
6. Create A database connnection in /connection/connect.js.
1  const mongoose = require('mongoose')
2
3  // Database
4  const connectDb = async () => {
5      try {
6          await mongoose.connect(process.env.MONGO_URI)
7          console.log("Connected to database")
8  
9      } catch (error) {
10          console.log(error)
11      }
12  }
7. Now import connectDb function in index.js file.
1  // Database
2  const connectDb = require('./connection/connect')
3  connectDb()
8. Now create a controllers folder in project root folder and create a mail.js file under controllers folder.
9.0 Before going to next point you should know about
Sender : -

Sender is like Info about sender like, which service use for send mail ?, sender's email address and password.

Mail : -

mail is info about email which was send by sender. mail have from which is sender email, to which is receiver email, subject is subject of email and text is text write in email.

9. In /controllers/mail.js import nodemailer and Create a sendMail function, under sendMail function create a sender by nodemailer.createTransport also write a mail and finally send mail by sender.sendMail.
1  const nodemailer = require("nodemailer")
2
3  exports.sendMail = async (req, res) => {
4  
5      let sender = nodemailer.createTransport({
6          service: 'Gmail',
7          auth: {
8              user: 'iamshiv20032003@gmail.com',
9              pass: process.env.PASS
10          }
11      })
12  
13      let mail = {
14          from: 'iamshiv20032003@gmail.com',
15          to: "shivrajg20032003@gmail.com",
16          subject: "test",
17          text: "Send a email using node.js"
18      }
19  
20      sender.sendMail(mail, function (error, info) {
21          if (error) {
22              res.status(500).json(error.message)
23          } else {
24              res.status(200).json("Email sent successfully" + info.response)
25          }
26      })
27  }
Note:- In sender, pass is not email password, to generate pass follow these steps.

1. Open chrome and go to settings menu.

2. Click on Manage your Google Account.

3. Search for app password and click on it.

4. Next Input your email password to verify.

5. select app = mail.

6. select window (in my case i select = Windows computer).

7. Click on GENERATE.

8. Next screen will Show your Password ๐ŸŽ‰.

10. Now create a routes folder in project root folder and create a mail.js and router.js file under routes folder.
11. For create api write this code under /routes/mail .
1  const router = require('express').Router()
2  const { sendMail } = require('../controllers/mail')
3  
4  router.route('/mail/new').post(sendMail)
5  
6  module.exports = router
12. Write this code under /routes/router .
1  const router = require('express').Router()
2
3  // mail routes
4  const mailRoute = require('./mail')
5  router.use('/', mailRoute)
6  
7  module.exports = mailRoute
13. And final step add api routes to our backend app /index .
1  // routes
2  const router = require('./routes/router')
3  app.use('/api', router)
Now you can test ๐Ÿ‘‰ http://localhost:yourport/api/mail/new
My Test response๐Ÿ˜ƒ
Email sent successfully250 2.0.0 OK 1686314142ย t1-20020aa79381000000b0064381853bfcsm2607717pfe.89 - gsmtp
14. To Attach a pdf or any attachment file.
a. simply add attachments field in mail like below.
d. Destructure originalname and buffer from req.file .
c. Also destructure email, subject and text from req.file .
1  const nodemailer = require("nodemailer")
2
3  exports.sendMail = (req, res) => {
4  
5      const { email, subject, text } = req.body
6      const { originalname, buffer } = req.file
7  
8      let sender = nodemailer.createTransport({
9          service: 'Gmail',
10          auth: {
11              user: 'iamshiv20032003@gmail.com',
12              pass: process.env.PASS
13          }
14      })
15  
16      let mail = {
17          from: 'iamshiv20032003@gmail.com',
18          to: email,
19          subject: subject,
20          text: text,
21          attachments: {
22              filename: originalname,
23              content: buffer
24          }
25      }
26  
27      sender.sendMail(mail, function (error, info) {
28          if (error) {
29              res.status(500).json(error.message)
30          } else {
31              res.status(200).json("Email sent successfully:" + info.response)
32          }
33      })
34  
35  }
15. install multer
npm i multer
16. Use multer in /routes/mail to get file in controller.
1  const router = require('express').Router()
2  const { sendMail } = require('../controllers/mail')
3  
4  const multer = require('multer')
5  const upload = multer()
6  
7  router.route('/mail/new').post(upload.single("attachment"), sendMail)
8  
9  module.exports = router
Note:- Make sure "attachment" string will same for file, when we hit post request.
Test again ๐Ÿ‘‰ http://localhost:yourport/api/mail/new
โค๏ธ Thank You ๐Ÿ™
Hello