DEV Community

Cover image for How to Send Emails via EmailJS in a Next.js Application
Full-stack Software Engineer
Full-stack Software Engineer

Posted on

How to Send Emails via EmailJS in a Next.js Application

When creating a web application, sending emails is often necessary for contact forms, notifications, and other purposes. Setting up your own SMTP server may seem overwhelming, but there are services like EmailJS that can handle email sending without the need for a backend. In this guide, I will demonstrate how to integrate EmailJS into your Next.js project, allowing you to easily send messages from your client-side application.

What is EmailJS?

EmailJS allows you to send emails directly from JavaScript without needing any server infrastructure. It connects to popular email services like Gmail, Outlook, and others, making it easier to send transactional emails directly from the frontend.

Let’s get started!

Step 1: Setting Up EmailJS

First, head over to EmailJS and sign up for an account. Once signed in:

  • Go to the Email Services section and select your email service (e.g., Gmail).

  • Set up a new Email Template. This template defines the structure of your email, and you can customize the fields to capture name, email, and message from your contact form.

  • Get your Service ID, Template ID, and User ID from the EmailJS dashboard, as you’ll need these in the code.

Step 2: Install EmailJS SDK

To use EmailJS in your project, you’ll need the EmailJS SDK. You can install it via npm or yarn:

npm install @emailjs/browser
# or
yarn add @emailjs/browser
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Contact Form

Let’s create a simple contact form that will allow users to send messages directly to your email. In Next.js, we can set up the form as a component.

Here’s an example of a Contact Form component:

"use client";
import { useState } from "react";
import { toast } from "react-toastify"; // For notifications
import emailjs from '@emailjs/browser';

function ContactForm() {
  const [userInput, setUserInput] = useState({
    name: "",
    email: "",
    message: ""
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setUserInput({
      ...userInput,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const serviceID = process.env.NEXT_PUBLIC_EMAILJS_SERVICE_ID;
    const templateID = process.env.NEXT_PUBLIC_EMAILJS_TEMPLATE_ID;
    const userID = process.env.NEXT_PUBLIC_EMAILJS_PUBLIC_KEY;

    try {
      const emailParams = {
        name: userInput.name,
        email: userInput.email,
        message: userInput.message
      };

      const res = await emailjs.send(serviceID, templateID, emailParams, userID);

      if (res.status === 200) {
        toast.success("Message sent successfully!");
        setUserInput({
          name: "",
          email: "",
          message: ""
        });
      }
    } catch (error) {
      toast.error("Failed to send message. Please try again later.");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Your Name:</label>
        <input
          type="text"
          name="name"
          value={userInput.name}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label>Your Email:</label>
        <input
          type="email"
          name="email"
          value={userInput.email}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label>Your Message:</label>
        <textarea
          name="message"
          value={userInput.message}
          onChange={handleChange}
          required
        />
      </div>
      <button type="submit">Send Message</button>
    </form>
  );
}

export default ContactForm;

Enter fullscreen mode Exit fullscreen mode

Breakdown:

  • useState: Manages form state (name, email, and message).

  • emailjs.send: Sends the email to your email service via EmailJS.

  • toast: Displays a notification on success or failure (optional, but you can install react-toastify to manage notifications).

Step 4: Environment Variables

To avoid hardcoding sensitive data (like service ID, template ID, and user ID), store them in environment variables. Create a .env.local file in the root of your project:

NEXT_PUBLIC_EMAILJS_SERVICE_ID=your_service_id
NEXT_PUBLIC_EMAILJS_TEMPLATE_ID=your_template_id
NEXT_PUBLIC_EMAILJS_PUBLIC_KEY=your_user_id
Enter fullscreen mode Exit fullscreen mode

Note: Be sure to restart your development server after adding or updating environment variables.

Step 5: Deploy Your App

Now that your contact form is integrated with EmailJS, it’s ready to be deployed. If you’re using Vercel, deploying a Next.js app is straightforward:

  • Push your code to GitHub or any Git provider.

  • Head over to the Vercel dashboard, connect your GitHub repository, and deploy your app.

Don’t forget to add the environment variables in your Vercel settings to ensure the email functionality works in production!

Conclusion

Integrating EmailJS with Next.js makes it incredibly easy to send emails directly from your frontend application without needing a backend server. It’s perfect for contact forms, feedback forms, or any other scenario where you need to send emails.

If you have any questions or run into issues, feel free to drop a comment below. Happy coding! 🚀

Top comments (0)