Sending emails to users from your server using Nodemailer, Node.js  and Gmail services

Sending emails to users from your server using Nodemailer, Node.js and Gmail services

Mail sending is an essential part of many app today in this article i simplify the process of integrating this complex feature into your app

Introduction

Mailing sending is an essential part of many applications today in this article I simplify the process of integrating this complex feature into your application

Nodemailer is an easy to use module for Node.js applications used for sending emails, in this article we'll dive into how we can set up our server/application to send emails to users/subscribers.

Configuring Gmail to get credentials for nodemailer connection

To get our password to access Gmail we would need to turn on two-factor authentication and create an app password which we'll be using. Below is how we can achieve this we first go to our security settings on gmail then:

  • Scroll to the How you sign in section then turn on Two step verification

  • After turning on the Two step verification you scroll down to the bottom where we have App passwords and select it

  • Then finally you enter the app name and select create

A unique 16-character password is created copy and store it in a safe place this passkey will be the password we use in nodemailer to connect to Gmail

Getting the project environment ready and setting things up

First, we create the folder where we'll have our project and move into the folder we just created

mkdir mail_project
cd mail_project/

We then initialize npm and install the required packages to set up a server and use nodemailer

npm init
npm install express body-parser nodemailer

Let's go ahead to create our server application inside our index.js file

//we import the necessary packages 
const express = require('express')
const nodemailer = require('nodemailer')
const bodyParser = require('body-parser')

const app = express()
app.use(bodyParser.urlencoded({ extended: true }))

app.listen(3000, function(){
    console.log("Server is running on port 3000")
})

With the little setup above you should have a server that runs on port 3000 you can test that by running node index.js in your terminal the output should be similar to what we have in the picture below

Now that we have an up and running server it's time to configure nodemailer we'll do this by using the createTransport method.

This method takes an object argument that has properties like service, host, port etc check the nodemailer documentation for all the properties that you can use. Below we'll use a few of those properties to set up a connection through which we can send our email

//transporter is the configuration we'll use to send our email
const transporter = nodemailer.createTransport({
    service: 'gmail', // we're using gmail as our service provider
    host: 'smtp.gmail.com', //Gmail's smtp server
    port: 465, //Port number for our connection
    secure: true, //This enables a secure connection
    auth: {
        user: process.env.USERNAME, //Your email goes here
        pass: process.env.PASSWORD, //Your app password(16 key generated in App passwords)
    },
})

At this point our nodemailer is fully configured and ready to send out mails therefore we'll create a simple endpoint that takes an email, subject and message from a user and sends it to the received email address

app.post("/api/sendMail", async function(req, res){
    const { email, subject, message } = req.body

    await transporter.sendMail({
        from: sender_email, //The sender's email goes here
        to: email, //The recipient email goes here
        subject: subject, //The subject of the email
        text: message
    }).catch(err => console.log(err)) 
})

Finally, we test our server using curl from our terminal

curl -X POST "http://localhost:3000/api/sendMail" -H "Content-Type: application/json"  -d '{ "email": "eugeneatinbire@gmail.com", "subject": "My first mail", "message": "Hello, this is my first email send from my nodejs app" }'

After running this command the recipient receives an email like in the image below

Do check out the nodemailer page for more information and properties you could use to suit the needs of your project or application.

Thanks for reading hope you found it educative.