Welcome folks today in this blog post we will be sending out messages
using the gmail api in node.js and express using the nodemailer
package in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new node.js
project using the below command as shown below
npm init -y
This will create the package.json file for the node.js project. Now we need to install the below packages as shown below
npm i express
npm i nodemailer
npm i multer
Express will be the webserver for this application and nodemailer will allow us to send out messages using the gmail api.
Now we need to create the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
const nodemailer = require("nodemailer"); const CLIENT_ID = "##yourclientid##"; const CLIENT_SECRET = "##yourclientsecret##"; async function sendEmail() { try { const transport = nodemailer.createTransport({ service: "gmail", auth: { type: "OAuth2", user: "geekygautam1997@gmail.com", clientId:CLIENT_ID, clientSecret:CLIENT_SECRET, accessToken: "##youraccesstoken##", }, }); const mailOptions = { from:"geekygautam1997@gmail.com", to:"sharmagautam1997dob@gmail.com", subject:"this is the test email", text:"hello this is the body of the email", html:"<h1>Hello World</h1>" } const result = await transport.sendMail(mailOptions) return result } catch (error) { console.log(error); } } sendEmail() .then((result) => { console.log("Email has been sent") }) .catch((error) => { console.log(`An ${error} occured`) }) |
As you can see guys you need to replace your clientid,clientsecret
& accesstoken of your cloud console account. First of all you can create the OAuth2 client id as shown below
And then for the accesstoken you need to go to https://developers.google.com/oauthplayground/ and from that you need to select the api and the scopes and then grant the permission and then exchange the authorization code with the access token as shown below
After getting the accessToken. Simply paste it inside the above script. Now if you run the node.js
app by the below command you will see the email will be received
node index.js
Sending Attachments in Nodemailer
Now guys we will be looking how we can send attachments also with the email in nodemailer. So now we need to slightly modify the code of index.js
as shown below
index.js
1 2 3 4 5 6 7 |
const mailOptions = { from:"geekygautam1997@gmail.com", to:"sharmagautam1997dob@gmail.com", subject:"this is the test email", text:"hello this is the body of the email", html:"<h1>Hello World</h1><img src='https://procodestore.com/wp-content/uploads/2021/03/164508084_271381191136191_654097929788476286_n.jpg'>" } |
As you can see we have added the <img>
tag and given the remote url of the image inside the html body of the email. So now the email will be sent and the image will be shown in the body of the html message as shown below
In order to add external attachments to the html
email you need to add the attachments object where you can add any type of media file such as image,video,text & pdf file as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const mailOptions = { from:"geekygautam1997@gmail.com", to:"sharmagautam1997dob@gmail.com", subject:"this is the test email", text:"hello this is the body of the email", html:"<h1>Hello World</h1><img src='https://procodestore.com/wp-content/uploads/2021/03/164508084_271381191136191_654097929788476286_n.jpg'>", attachments:[ { filename:"file.txt", content:"This is the content of the text file" }, { filename:"image.png", path:"https://i.pinimg.com/originals/e0/11/7e/e0117e09a02b4d2ac866d8e7d57db38e.jpg" }, { filename:"sample.pdf", path:"https://www.africau.edu/images/default/sample.pdf" } ] } |
As you can see we have added the attachments property to the mailOptions Object. Inside it we have an array of attachments and each attachment contains two properties filename and content for the text file. And filename and path for providing the remote url images and pdf documents. Now if you send this email you will receive the attachments as shown below
And after that if you want to send a local image
file which is stored inside the computer then the code will look like this as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const mailOptions = { from:"geekygautam1997@gmail.com", to:"sharmagautam1997dob@gmail.com", subject:"this is the test email", text:"hello this is the body of the email", html:"<h1>Hello World</h1><img src='https://procodestore.com/wp-content/uploads/2021/03/164508084_271381191136191_654097929788476286_n.jpg'>", attachments:[ { filename:"image.png", path:"image.png" } ] } |
In this case also you just need to provide the path of the stored local image in your computer or laptop and give the path inside the above code
Express App to Send Email in Browser
Now guys we will be using the express
and the multer
library to allow users to upload images inside the browser and send emails using the nodemailer
library. For this we need to create the index.js
file and copy paste the below code
Now you also need to create the public
folder where all the static stuff will be there for the express app. Here we are storing the index.html
which will be shown to the user and also create a uploads folder where all the uploaded images will be stored
Now just create the index.html
which is a simple html5 form
where it contains the input field to allow users to upload multiple files and a submit button
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Nodemailer send Email</title> </head> <body> <form action="/sendemail" method="post" enctype="multipart/form-data"> <input type="file" name="file" multiple required id=""> <input type="submit" value="Send Email"> </form> </body> </html> |
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
const express = require("express"); const path = require("path"); const multer = require("multer"); const bodyparser = require('body-parser') const nodemailer = require("nodemailer"); const CLIENT_ID = "##yourclientid##"; const CLIENT_SECRET = "##yourclientsecret##"; const ACCESS_TOKEN = "##youraccesstoken##" const app = express(); let paths = []; let subject="" let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/uploads"); }, filename: function (req, file, cb) { cb(null, Date.now() + path.extname(file.originalname)); }, }); let upload = multer({ storage: storage }).array("file", 100); const port = 4000; app.use(express.static("public")); app.use(bodyparser.urlencoded({ extended: false })); app.use(bodyparser.json()); app.get("/", (req, res) => { res.sendFile("index.html"); }); app.post("/sendemail", (req, res) => { subject = req.body.text console.log(subject) upload(req, res, (err) => { if (err) { console.log("Some error occured"); } else { console.log(req.files); req.files.forEach((file) => { paths.push({ filename: Date.now() + "file" + path.extname(file.originalname), path: file.path, }); }); console.log(paths); sendEmail(paths,subject) .then((result) => { console.log("Email has been sent") }) .catch((error) => { console.log(`An ${error} occured`) }) } }); }); async function sendEmail(paths,subject) { try { const transport = nodemailer.createTransport({ service: "gmail", auth: { type: "OAuth2", user: "geekygautam1997@gmail.com", clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, accessToken: ACCESS_TOKEN, }, }); const mailOptions = { from: "geekygautam1997@gmail.com", to: "sharmagautam1997dob@gmail.com", subject: subject, text: `hello this is the body of the ${subject} message`, html: "<h1>Hello World</h1>", attachments:paths }; const result = await transport.sendMail(mailOptions); return result; } catch (error) { console.log(error); } } app.listen(port, () => { console.log("App is listening on port 4000"); }); |
We are just slightly modified the script from early on. We have imported the express and the multer library and then we are showing the index.html
file when user opens the home page and also we are setting the config for the multer library. And then we are making the post request when users submit the form this request will automatically execute and here we are getting the uploaded files using the multer constructor and then appending the paths of the files uploaded. And lastly we are calling the sendEmail()
method where we are sending the email using nodemailer.