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
We can deploy the app on Heroku in such a way that we can run the service from any other application by invoking it via an HTTP call, to do so you can follow this guide I wrote recently:
⭐️ Bonus: Try it in my application!
I used this system to send email summaries to users of my service https://quickview.email/try-summary, it allows you to summarize YouTube videos in your desired language and receive it by email, try it for free!
I published a post where I explained how I implemented this system using scraping and ChatGPT, you can find it here:
📚 Top lectures of the week
How to better structure your next Node.js project? The Modular Approach.
😎 My strategy to become a TOP 1% engineer
Stick to boring architecture for as long as possible.
And that’s it for today! If you are finding this newsletter valuable, consider doing any of these:
🍻 Read with your friends — Implementing lives thanks to word of mouth. Share the article with someone who would like it.
📣 Provide your feedback — We welcome your thoughts! Please share your opinions or suggestions for improving the newsletter, your input helps us adapt the content to your tastes.
💬 Chat with me — If you have any doubts or curiosity, please write to me, I will be happy to answer you!
I wish you a great day! ☀️
Marco
I also used nodemailer in the past. Great article, Marco. And thank you for the mention!
Interesting build! I think it's beneficial for any Node.js user to build it. Thanks for the great content, Marco!