DEV Community

Yug Jadvani
Yug Jadvani

Posted on

How to Set Up a Node.js Project with Typescript and Send Emails Using Nodemailer

Inthe ever-evolving world of software engineering, communication is key. Imagine a user signing up for your application and instantly receiving a personalized welcome email. This guide walks you through setting up a Node.js project with TypeScript and configuring it to send emails using Nodemailer a must have skills for developers working on modern web applications.

Let’s dive into the story of how we make it happen, step by step.


The Journey Begins: Setting Up Your Node.js Project

it was a quite evening, and I decided to automate user onboarding emails for a project I was working on. The first step was to set up a robust Node.js project with TypeScript.

Step 1: Initialize Your Project

Start by creating a directory and initializing a Node.js project.

mkdir email-project
cd email-project
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Add TypeScript

TypeScript ensures type safety, making your project maintainable. Install TypeScript and initialize it.

npm install typescript --save-dev
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

This generates a tsconfig.json file. Update it as needed.


Installing Nodemailer

To send emails, we’ll use Nodemailer, a powerful email-sending library.

npm install nodemailer
npm install -D @types/nodemailer
Enter fullscreen mode Exit fullscreen mode

Now, we’re all set with the tools we need to send that magic email.


Creating a Secure Environment

Sending emails requires sensitive information such as your email credentials. To keep things secure, we’ll use environment variables.

Step 1: Create an App Password

  1. Go to Manage Your Google Account.
  2. Search for App Passwords in the settings.
  3. Sign in if prompted.
  4. Create an app password for your project and node it down securely.

Step 2: Create a .env File

At the root of your project, create a .env file to store your credentials:

EMAIL_USER='your_email@example.com'
EMAIL_PASSWORD='your_app_password'
Enter fullscreen mode Exit fullscreen mode

Install the dotenv package to load environment variables into your project:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

Configuring Nodemailer

It was time to bring it all together. The following code configures Nodemailer to use your credentials and Gmail's SMTP services:

import nodemailer from 'nodemailer';
import dotenv from 'dotenv';

dotenv.config();

const configOptions = {
  host: 'smtp.gmail.com',
  port: 587,
  secure: true,
  service: 'gmail',
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASSWORD,
  },
};

const transporter = nodemailer.createTransport(configOptions);

export default transporter;
Enter fullscreen mode Exit fullscreen mode

Creating the Email Template

One of the most exciting parts of this project was crafting a beautiful email template. Here’s how I did it:

import { SendMailOptions } from 'nodemailer';
import transporter from './utils/nodemailer';

interface User {
  name: string;
  email: string;
}

export const sendUserWelcomeEmail = async (user: User) => {
  try {
    const mailOptions: SendMailOptions = {
      from: process.env.EMAIL_USER,
      to: user.email,
      subject: `Welcome, ${user.name}!`,
      html: `
      <!DOCTYPE html>
      <html>
        <body>
          <h1>Welcome to Our Platform, ${user.name}!</h1>
          <p>We're excited to have you onboard. Get started by exploring our features!</p>
        </body>
      </html>`,
    };

    await transporter.sendMail(mailOptions);
    console.log('Welcome email sent!');
  } catch (error) {
    console.error('Error sending email:', error);
  }
};
Enter fullscreen mode Exit fullscreen mode

Sending the Email

Finally, it was time to see it all in action. Here’s how you send the email:

await sendUserWelcomeEmail({
  name: 'John Doe',
  email: 'john.doe@example.com',
});
Enter fullscreen mode Exit fullscreen mode

I’II never forget the first time I ran this script. Seeing the email arrive in the inbox felt magical.


Why This Matters

This simple setup goes a long way in improving user experience. Whether you’re building a SaaS platform or an e-commerce app, automated emails can create a seamless onboarding journey.


Becoming a Master of Your Tools

With this guide, you’re built a strong foundation. Keep experimenting and refining your skills. Remember, every great developer was once a beginner who dared to try something new.

Stay carious, keep building, and happy coding!

Top comments (0)