Hey, I'm Marco and welcome to my newsletter!
As a software engineer, I created this newsletter to share my first-hand knowledge of the development world. Each topic we will explore will provide valuable insights, with the goal of inspiring and helping all of you on your journey.
In this episode, I'll show you how to set up an email sending system using Node.js with a Gmail account.
You can download all the code shown directly from my Github repository: https://github.com/marcomoauro/mailer
👋 Introduction
One of the first projects I did was to create a simple script for sending e-mails. I was excited about the idea of sending messages for free, just like most websites do.
Email is a straightforward and effective system. All you need is an address to send a message.
We will refer to Gmail, but the same applies to other email providers. If you are interested in how to do the setup, let me know in the comments.
Alternatives
Another simple notification system, besides e-mail, could be the use of a Telegram group where a Bot sends messages to the channel via Webhook.
A downside is that, unlike e-mail, it requires an initial set-up where users have to be added to the group.
I show how to create Telegram bots and set up webhooks in this post:
⚙️ Configure Gmail account
To use your Gmail account for sending emails, you'll first need to create a new “app” within your account settings. Here are the steps to follow:
enable 2FA
Go to the Security panel of your Google account via this link https://myaccount.google.com/u/2/security and activate the two-step verification, it is a necessary step to proceed with the creation of the app.
create new app
from this link https://myaccount.google.com/apppasswords proceed to create the app, all you have to do is choose a name. A password will be generated, which you will use to send emails with the nodemailer library.
I found this information on stackoverflow, it saved me from wasting hours trying to configure it myself. 🙏
👨💻 Let’s get down to practice
You can download all the code shown directly from my Github repository: https://github.com/marcomoauro/mailer
Nodemailer
For sending e-mails, I relied on the nodemailer library, which is the default solution for most Node.js users.
Implementation
For the implementation I used my template in Node.js, you can find it here:
Set up the environment variables by specifying in the .env file the email and password previously generated
MAILER_USER=<YOUR-GOOGLE-MAIL>
MAILER_PASSWORD=<APP-PASSWORD>
We create the file mailer.js, it takes care of exposing the primitives of the nodemailer library to enable the correct sending of e-mails:
import nodemailer from 'nodemailer';
import log from "../log.js";
import {strict as assert} from 'assert';
assert(process.env.MAILER_USER, 'MAILER_USER env is required, define it in .env file')
assert(process.env.MAILER_PASSWORD, 'MAILER_PASSWORD env is required, define it in .env file')
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.MAILER_USER,
pass: process.env.MAILER_PASSWORD
}
});
export const sendMailApi = async ({email, subject, body}) => {
log.info('API::Mailer::sendMailApi', {email, subject, body});
const response = await transporter.sendMail({
from: process.env.MAILER_USER,
to: email,
subject,
text: body,
});
return response;
}
we create the controller mailer.js which will be responsible for receiving parameters from the api and sending them to the service:
import log from "../log.js";
import {sendMailApi} from "../api/mailer.js";
export const sendMail = async ({email, subject, body}) => {
log.info('Controller::Mailer::sendMail', {email, subject, body});
await sendMailApi({email, subject, body});
return {
message: 'Mail sent'
};
}
and finally create a new api in the router.js file:
import {sendMail} from "./controllers/mailer.js";
router.post('/send-mail', routeToFunction(sendMail));
How to test
You can verify the proper operation by starting the server with:
yarn serve:development
and making a call to the new endpoint with:
curl --location 'http://localhost/send-mail' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "marcomoauro@hotmail.it",
"subject": "Test Subject from Node.js Mailer",
"body": "Example body for Implementing post"
}'
Deploy
Keep reading with a 7-day free trial
Subscribe to Implementing to keep reading this post and get 7 days of free access to the full post archives.