Next.js - Send Mails using Nodemailer

There is no need to spend money on 3rd Party APIs when you can send E-Mails in Next.js using Nodemailer.

All that is needed is an E-Mail account at any provider; often, webspaces already offer a mail account in combination with the webspace.

The following code snippet can be used to send mails from the mail account after installing the package by using a command such as npm install nodemailer. There are also plugins and a lot of configurations available on the website as well. The documentation is worth a look for more sophisticated setups; this is a base version as a simple POC.

import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "{MAIL_HOST}",
  port: {MAIL_PORT},
  secure: true,
  auth: {
    user: "{MAIL_USER}",
    pass: "{MAIL_PASS}",
  },
  disableFileAccess: true,
  disableUrlAccess: true,
});

try {
  await transporter.verify();
  console.log("Server is ready to take our messages");
} catch (err) {
  console.error("Verification failed", err);
}

async function sendEmail() {
  try {
    const info = await transporter.sendMail({
      // More Settings: https://nodemailer.com/message#common-fields
      from: '"Hitori Health" <{MAIL_SENDER}>',
      to: "{MAIL_RECIEVER}",
      subject: "Hello",
      text: "Hello world?",
      html: "<b>Hello world?</b>",
    });

    console.log("Message sent: %s", info.messageId);
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  } catch (err) {
    console.error("Error while sending mail", err);
  }
}

export default function Home() {
  sendEmail();
  return (
    <main>
      <h1 className="text-4xl font-bold">Welcome</h1>
    </main>
  );
}

Replace {MAIL_HOST} and {MAIL_PORT} with the SMTP server settings, {MAIL_USER} and {MAIL_PASS} with valid credentials for the account, {MAIL_SENDER} with the E-Mail address you are sending from, and {MAIL_RECIEVER} with the receiver’s mail address.

Comments