<Sagar/>

Next.js Email: Google SMTP Step By Step With Example Code

47

In this blog, I’ll walk you through a step-by-step guide to send emails using Google SMTP in your Next.js app. We’ll use the popular nodemailer package to handle email functionality.

Not a premium member READ HERE

Prerequisites

  • A Next.js app (you can create one using npx create-next-app).

  • A Gmail account.


Step 1: Enable Google SMTP Access

Google provides free SMTP services through Gmail, but you need to configure your account:

Enable Less Secure App Access:

OR

Create an App Password (Recommended for Better Security):

  • Go to your Google Account.

  • Navigate to Security > 2-Step Verification and enable it.

  • Under “Signing in to Google,” select App Passwords and generate one for your application.

Note down your Gmail email address and the app password.


Step 2: Install Dependencies

We’ll use the nodemailer library to handle SMTP email sending.

Run the following command:

npm install nodemailer

Step 3: Create an API Route for Sending Emails

Next.js API routes allow you to build server-side functionality. Create an API endpoint to handle email-sending logic.

Create a file pages/api/sendEmail.js:

import nodemailer from 'nodemailer';
export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Method not allowed' });
  }const { to, subject, text } = req.body;
if (!to || !subject || !text) {
    return res.status(400).json({ message: 'Missing required fields' });
  }
try {
    const transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: process.env.EMAIL_USER, // Your Gmail address
        pass: process.env.EMAIL_PASS, // Your Gmail app password
      },
    });
const mailOptions = {
      from: process.env.EMAIL_USER,
      to,
      subject,
      text,
    };
await transporter.sendMail(mailOptions);
    res.status(200).json({ message: 'Email sent successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Failed to send email', error: error.message });
  }
}

Step 4: Add Environment Variables

For security, never hard-code sensitive information like email credentials in your code. Use environment variables instead.

Create a .env.local file in the root of your project:

EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password

Restart your development server to apply the environment variables.


Step 5: Create a Frontend Form to Trigger Emails

Let’s build a simple form that users can use to send emails.

Create a file pages/email.js:

import { useState } from 'react';
export default function Email() {
  const [formData, setFormData] = useState({ to: '', subject: '', text: '' });
  const [response, setResponse] = useState('');
const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };
const handleSubmit = async (e) => {
    e.preventDefault();
    setResponse('');
try {
      const res = await fetch('/api/sendEmail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
const data = await res.json();
      setResponse(data.message);
    } catch (error) {
      setResponse('Error sending email.');
    }
  };
return (
    <div>
      <h1>Send Email</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="email"
          name="to"
          placeholder="Recipient Email"
          value={formData.to}
          onChange={handleChange}
          required
        />
        <input
          type="text"
          name="subject"
          placeholder="Subject"
          value={formData.subject}
          onChange={handleChange}
          required
        />
        <textarea
          name="text"
          placeholder="Message"
          value={formData.text}
          onChange={handleChange}
          required
        />
        <button type="submit">Send Email</button>
      </form>
      {response && <p>{response}</p>}
    </div>
  );
}

Step 6: Test Your Setup

Start your Next.js development server:

npm run dev
  1. Visit http://localhost:3000/email in your browser.

  2. Fill out the form and submit it. Check the recipient’s inbox for the email.


Troubleshooting

  • Authentication Error: Ensure you’ve entered the correct Gmail email and app password.

  • Environment Variables Not Working: Restart the server after updating .env.local.

  • Email Delays: Check your Gmail account for any throttling or spam-related issues.

🔥 Found this blog post helpful? 🔥

If you enjoyed this article and found it valuable, please show your support by clapping 👏 and subscribing to my blog for more in-depth insights on web development and Next.js!

Subscribe here: click me

Your encouragement helps me continue creating high-quality content that can assist you on your development journey. 🚀

JavaScript
Next.js
Frontend
Node.js
Web Development
Arnold Gunter

Written by Sagar Sangwan

👨‍💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!

View more blogs by me CLICK HERE

Loading related blogs...

Newsletter subscription

SUBSCRIBE to Newsletter

In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.