Securely Send Emails in Next.js with Gmail SMTP

30 September 2025



This blog shows exactly how to generate Gmail App Passwords and configure the essential SMTP keys in your Next.js project for sending emails using Gmail, Nodemailer, SendGrid, or any email provider.


1. Enable 2-Step Verification

Go to your Google Account Security settings and enable 2-Step Verification if it’s not already enabled, as shown in Figure 1.


Google account 2-Step verification Figure 1

2. Navigate to App Passwords

In your Google Account, go to App Passwords, as shown in Figure 2.


Google App Passwords page Figure 2

3. Generate App Password

Enter an app name of your choice and press Create, as shown in Figure 3.


Generate Gmail App Password Figure 3

4. Copy the 16-Character Password

Copy the 16-character password generated by Google, as shown in Figure 4.


Gmail 16 character app password

Figure 4


5. Paste Keys in .env File

Add the required SMTP configuration into your project’s .env file:


SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=youremail@gmail.com
SMTP_PASS=your-16-character-app-password
  

By storing these values securely in your .env file and using a library like Nodemailer or SendGrid, you can send emails reliably for contact forms, authentication, or transactional notifications in your Next.js application.


📧 Sending Emails Using Nodemailer

After configuring SMTP keys, you can send emails using Nodemailer. Always send emails from the server (Next.js API route or Node.js backend).

Install Nodemailer


npm install nodemailer
  

Reusable email sending function


import nodemailer from "nodemailer";

export async function sendEmail(to: string, subject: string, html: string) {
  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: false,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  await transporter.sendMail({
    from: `"My App" <${process.env.SMTP_USER}>`,
    to,
    subject,
    html,
  });
}

Custom email template


export function contactEmailTemplate(name: string, message: string) {
  return `
    <div style="font-family: Arial; line-height: 1.6">
      <h2>New Contact Message</h2>
      <p><strong>Name:</strong> ${name}</p>
      <p><strong>Message:</strong></p>
      <p>${message}</p>
    </div>
  `;
}
  

Simple usage (Next.js API or Node.js)


await sendEmail(
  "youremail@gmail.com",
  "New Contact Message",
  contactEmailTemplate("John Doe", "Hello, I need help!")
);
  

💡 Tip: This call should be executed inside a server-side environment such as a Next.js API route or Node.js backend — never from client-side code.