NodeMail in NextJS

"How can you send mail in your NextJS project "

By Seepseek

2022-02-02

NodeMail in NextJS

How to Use Nodemailer in Next.js with Gmail

In this guide, we'll walk through how to set up Nodemailer in a Next.js application to send emails using Gmail. We'll cover everything from setting up environment variables to creating the API route and form.


Step 1: Install Nodemailer

First, install the nodemailer package in your Next.js project:

npm install nodemailer

Step 2: Set Up Environment Variables

To securely store your Gmail credentials, you'll need to set up environment variables. Here's how to do it:

  1. Create a .env.local file in the root of your project.
  2. Add the following environment variables to the file:
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-gmail@gmail.com
EMAIL_PASS=your-gmail-app-password

Important Notes for Gmail:


Step 3: Create an API Route for Sending Emails

Next.js uses API routes to handle server-side logic. Create a new file in the pages/api directory, e.g., pages/api/send-email.js, and add the following code:

import nodemailer from 'nodemailer';
 
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, message } = req.body;
 
    // Create a Nodemailer transporter
    const transporter = nodemailer.createTransport({
      host: process.env.EMAIL_HOST,
      port: process.env.EMAIL_PORT,
      secure: false, // true for 465, false for other ports
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });
 
    // Define email options
    const mailOptions = {
      from: `"${name}" <${email}>`,
      to: process.env.EMAIL_USER, // Send to your own email
      subject: `New message from ${name}`,
      text: message,
      html: `<p>${message}</p>`,
    };
 
    try {
      // Send the email
      await transporter.sendMail(mailOptions);
      res.status(200).json({ message: 'Email sent successfully!' });
    } catch (error) {
      console.error('Error sending email:', error);
      res.status(500).json({ message: 'Failed to send email.' });
    }
  } else {
    res.status(405).json({ message: 'Method not allowed.' });
  }
}

Step 4: Create a Form in Your Next.js App

Now, create a form in your Next.js app to collect user input and send it to the API route. For example, in pages/contact.js:

import { useState } from 'react';
 
export default function Contact() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: '',
  });
  const [status, setStatus] = useState('');
 
  const handleSubmit = async (e) => {
    e.preventDefault();
 
    const response = await fetch('/api/send-email', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });
 
    const result = await response.json();
    setStatus(result.message);
  };
 
  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };
 
  return (
    <div>
      <h1>Contact Us</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label htmlFor="message">Message:</label>
          <textarea
            id="message"
            name="message"
            value={formData.message}
            onChange={handleChange}
            required
          />
        </div>
        <button type="submit">Send</button>
      </form>
      {status && <p>{status}</p>}
    </div>
  );
}

Step 5: Test the Email Functionality

  1. Start your Next.js development server:
    npm run dev
  2. Navigate to the contact form page (e.g., http://localhost:3000/contact).
  3. Fill out the form and submit it.
  4. Check your email inbox to confirm that the email was sent successfully.

Step 6: Deploy to Production

When deploying your Next.js app to production (e.g., Vercel, Netlify), make sure to add your environment variables to the deployment platform. Most platforms provide a way to configure environment variables in their dashboard.

For example, in Vercel:

  1. Go to your project dashboard.
  2. Navigate to Settings > Environment Variables.
  3. Add the same environment variables (EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS) with their respective values.

Troubleshooting

Common Issues with Gmail

  1. App Password Not Working:

    • Ensure 2-Step Verification is enabled in your Google Account.
    • Double-check that you generated the App Password correctly.
  2. Blocked by Gmail:

    • Gmail may block sign-in attempts from less secure apps. To fix this:
      • Go to your Google Account.
      • Navigate to Security > Less secure app access and enable it.
  3. Rate Limits:

    • Gmail has daily sending limits. If you exceed these limits, consider using a dedicated email service like SendGrid or Mailgun.

Conclusion

By following this guide, you can easily set up Nodemailer in your Next.js app to send emails using Gmail. Remember to use an App Password for authentication and secure your environment variables when deploying to production.

This guide provides a detailed walkthrough of setting up Nodemailer in a Next.js app with Gmail, including environment variable setup and deployment tips. Let me know if you need additional help!

Comments

avatar

Jhon Doe

20 October, 2018

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Accusamus numquam assumenda hic aliquam vero sequi velit molestias doloremque molestiae dicta?

avatar

Rob Simpson

20 October, 2018

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Accusamus numquam assumenda hic aliquam vero sequi velit molestias doloremque molestiae dicta?

Leave a comment