logo icon

OKSANA

KOROBANOVA

grey and black metal tool
Back to all posts

Next.js email sender

Send dynamic emails using Next.js, nodemailer, handlebars


Date:


Introduction

Email communication is a crucial aspect of many web applications. In this guide, we'll explore how to send dynamic emails using Next.js, Nodemailer, and Handlebars. The provided code snippets demonstrate a simple implementation for sending emails and working with templates.

Setting Up Your Next.js Project

Begin by creating a new Next.js project if you haven't already:

1npx create-next-app my-email-app
2cd my-email-app

Install the required dependencies:

1npm install nodemailer handlebars

Sending Emails with Nodemailer

First, let's set up a utility function for sending emails. Create a file named mail.ts inside the lib folder:

1// src/lib/mail.ts
2
3import nodemailer from 'nodemailer';
4type Mail = {
5  to: string;
6  subject: string;
7  body: string;
8};
9
10export async function sendMail({ to, subject, body }: Mail) {
11  const { SMTP_EMAIL_FROM, SMTP_PASSWORD } = process.env;
12
13  const transport = nodemailer.createTransport({
14    service: 'gmail',
15    auth: {
16      user: SMTP_EMAIL_FROM,
17      pass: SMTP_PASSWORD,
18    },
19  });
20
21  try {
22    await transport.verify();
23  } catch (error) {
24    console.log(error);
25    return;
26  }
27
28  try {
29    await transport.sendMail({
30      from: `From <${SMTP_EMAIL_FROM}>`,
31      to,
32      subject,
33      html: body,
34    });
35  } catch (error) {
36    console.log(error);
37  }
38}
39

Working with Handlebars Templates

Now, let's create a Handlebars template. Inside the lib/templates folder, create a file named discount.ts:

1// lib/templates/discount.ts
2
3export const discount = `
4  <html>
5    <head>
6      <title>Discount Email</title>
7    </head>
8    <body>
9      <p>Hello {{ name }},</p>
10      <p>Congratulations! You've received a special discount.</p>
11    </body>
12  </html>
13`;

Compiling Handlebars Templates

Add a function to compile Handlebars templates in the lib/mail.ts file:

1// src/lib/mail.ts
2
3import nodemailer from 'nodemailer';
4import * as handlebars from 'handlebars';
5import { discount } from './templates/discount';
6
7export function compileTemplate(name: string) {
8  const template = handlebars.compile(discount);
9  const htmlBody = template({ name: name });
10  return htmlBody;
11}

Integrating in a Next.js Page

Now, let's use these functionalities in a Next.js page. Open app/page.tsx:

1// app/page.tsx
2
3import styles from './page.module.css';
4import { compileTemplate, sendMail } from '@/lib/mail';
5
6const send = async () => {
7  'use server';
8  await sendMail({
9    to: process.env.SMTP_EMAIL_TO as string, // just take it from the real form
10    subject: 'Test email sending',
11    body: compileTemplate('Hanna'),
12  });
13};
14
15export default function Home() {
16  return (
17    <main className={styles.main}>
18      <form>
19        <button formAction={send}>Send email</button>
20      </form>
21    </main>
22  );
23}

Ensure that you have the necessary environment variables set up for your SMTP configuration (SMTP_EMAIL_FROM, SMTP_PASSWORD, and SMTP_EMAIL_TO).

This implementation allows you to send dynamic emails using Nodemailer and Handlebars within a Next.js application. Customize the templates and functionalities based on your specific use case.