Next.js: Sending Emails with Nodemailer and SMTP in a Next.js 14 App Using the App Router Email Client

Posted by

<!DOCTYPE html>

How to Send Emails in Next.js Using Nodemailer and SMTP

How to Send Emails in Next.js Using Nodemailer and SMTP

Sending emails in a Next.js application can be a useful feature for a wide range of use cases, such as sending notifications, newsletters, or verification emails. In this article, we will walk through how to set up and send emails in a Next.js application using Nodemailer and SMTP.

Prerequisites

Before we can start sending emails in Next.js, we need to make sure we have the following prerequisites:

  • A Next.js 14 app set up and running
  • Nodemailer installed in our Next.js project
  • An SMTP server to send emails through (such as Gmail, SendGrid, or Amazon SES)

Setting up Nodemailer

First, we need to install Nodemailer in our Next.js project. We can do this by running the following command in our project directory:

npm install nodemailer

Once Nodemailer is installed, we can create a new file (e.g., `email.js`) in our Next.js project where we will write the code to send emails. In this file, we need to require Nodemailer and set up a transporter using our SMTP server credentials.

Sending an Email

With our Nodemailer setup in place, we can now write the code to send an email in our Next.js application. For example, to send a basic email with a subject and text body, we can use the following code:

// require Nodemailer
const nodemailer = require('nodemailer');

// create a transporter using SMTP settings
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,
  auth: {
    user: 'your-email@example.com',
    pass: 'your-email-password'
  }
});

// send an email
transporter.sendMail({
  from: 'your-email@example.com',
  to: 'recipient@example.com',
  subject: 'Testing Nodemailer in Next.js',
  text: 'This is a test email sent from a Next.js app using Nodemailer and SMTP.'
}, (error, info) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Conclusion

In this article, we have learned how to send emails in a Next.js application using Nodemailer and SMTP. By following the steps outlined above and customizing the code to fit our specific use case, we can easily integrate email functionality into our Next.js app.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@martinkarugaba
1 month ago

Thanks @ZestMade. How can I adjust this to send to a gmail account?

@khanhlinhinh50
1 month ago

Thank you so much for this tutorials.
The knowledge you teach in this video really helps in my project
Can you make a video about upload and download files using nest js and next js?

@nanonkay5669
1 month ago

Does this work with real email addresses or just fake ones?