Email Nextjs
- Atul
- Programming
- May 13, 2024
Table of Contents
How to send mail using Nodemailer in NextJS
"use server";
import nodemailer from "nodemailer";
export default async function sendEmail(
toEmail: string,
subject: string,
text: string
) {
const password = process.env.EMAIL_PASSWORD;
const host = process.env.EMAIL_HOST;
const user = process.env.EMAIL_USERNAME;
console.log(typeof process.env.EMAIL_PASSWORD);
try {
// Create a Nodemailer transporter with your email provider's settings
const transporter = nodemailer.createTransport({
port: 465,
host: host,
auth: {
user: user,
pass: password,
},
});
// Send the email
const info = await transporter.sendMail({
from: "YourEmail@address.here",
to: toEmail,
subject: subject,
text: text,
});
console.log("Message sent: %s", info.messageId);
} catch (error) {
console.error("Error sending email:", error);
}
}
“use server” for NextJS to use this code in server.
.env
file
EMAIL_USERNAME='add your email address here'
EMAIL_PASSWORD=your password
EMAIL_HOST='email host here'
EMAIL_SERVER_PORT=465
As sendEmail is a function exported, you can use it anywhere in your code.
Updates: July 30 2024
This is a Nextjs app, so you might host it in Vercel.
I faced an error there:
Error sending email: Error: connect ECONNREFUSED 127.0.0.1:465 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1606:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) { errno: -111, code: 'ESOCKET', syscall: 'connect', address: '127.0.0.1', port: 465, command: 'CONN' }
This was solved by:
Changing the port from 465 to 587