In this blog, I’ll walk you through a step-by-step guide to send emails using Google SMTP in your Next.js app. We’ll use the popular nodemailer
package to handle email functionality.
A Next.js app (you can create one using npx create-next-app
).
A Gmail account.
Google provides free SMTP services through Gmail, but you need to configure your account:
Enable Less Secure App Access:
Turn on “Less secure app access.”
OR
Create an App Password (Recommended for Better Security):
Go to your Google Account.
Navigate to Security > 2-Step Verification and enable it.
Under “Signing in to Google,” select App Passwords and generate one for your application.
Note down your Gmail email address and the app password.
We’ll use the nodemailer
library to handle SMTP email sending.
Run the following command:
npm install nodemailer
Next.js API routes allow you to build server-side functionality. Create an API endpoint to handle email-sending logic.
Create a file pages/api/sendEmail.js
:
import nodemailer from 'nodemailer';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}const { to, subject, text } = req.body;
if (!to || !subject || !text) {
return res.status(400).json({ message: 'Missing required fields' });
}
try {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER, // Your Gmail address
pass: process.env.EMAIL_PASS, // Your Gmail app password
},
});
const mailOptions = {
from: process.env.EMAIL_USER,
to,
subject,
text,
};
await transporter.sendMail(mailOptions);
res.status(200).json({ message: 'Email sent successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Failed to send email', error: error.message });
}
}
For security, never hard-code sensitive information like email credentials in your code. Use environment variables instead.
Create a .env.local
file in the root of your project:
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password
Restart your development server to apply the environment variables.
Let’s build a simple form that users can use to send emails.
Create a file pages/email.js
:
import { useState } from 'react';
export default function Email() {
const [formData, setFormData] = useState({ to: '', subject: '', text: '' });
const [response, setResponse] = useState('');
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
setResponse('');
try {
const res = await fetch('/api/sendEmail', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
const data = await res.json();
setResponse(data.message);
} catch (error) {
setResponse('Error sending email.');
}
};
return (
<div>
<h1>Send Email</h1>
<form onSubmit={handleSubmit}>
<input
type="email"
name="to"
placeholder="Recipient Email"
value={formData.to}
onChange={handleChange}
required
/>
<input
type="text"
name="subject"
placeholder="Subject"
value={formData.subject}
onChange={handleChange}
required
/>
<textarea
name="text"
placeholder="Message"
value={formData.text}
onChange={handleChange}
required
/>
<button type="submit">Send Email</button>
</form>
{response && <p>{response}</p>}
</div>
);
}
Start your Next.js development server:
npm run dev
Visit http://localhost:3000/email
in your browser.
Fill out the form and submit it. Check the recipient’s inbox for the email.
Authentication Error: Ensure you’ve entered the correct Gmail email and app password.
Environment Variables Not Working: Restart the server after updating .env.local
.
Email Delays: Check your Gmail account for any throttling or spam-related issues.
🔥 Found this blog post helpful? 🔥
If you enjoyed this article and found it valuable, please show your support by clapping 👏 and subscribing to my blog for more in-depth insights on web development and Next.js!
Subscribe here: click me
Your encouragement helps me continue creating high-quality content that can assist you on your development journey. 🚀
👨💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!
View more blogs by me CLICK HERE
Loading related blogs...
In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.