How to Send Email in Next.js and Node.js for FREE - With MailAPI.dev
Learn to integrate MailAPI.dev in your Next.js app. This guide shows you how to use the official NPM package to handle all your app's email needs

Sending transactional emails is a crucial feature for most modern web applications.
That’s why you should use MailAPI.dev — a developer-first email API that makes sending emails as simple as making a fetch request. Whether you’re building a Next.js app, a Node.js backend, or any JavaScript application, MailAPI.dev gives you everything you need to handle emails without the headache.
What Makes MailAPI.dev Different?
MailAPI.dev isn’t just another email service — it’s a complete email infrastructure solution designed specifically for developers who want to move fast. Here’s what you get:
✅ Email Verification
✅ Email Verification
📧 Email Templates
💾 Email Storage
⚡ Email Automation
Watch It In Action
Before we dive into the code, here’s a quick video tutorial showing how easy it is to get started:
Getting Started with MailAPI.dev in Next.js
Let me show you how ridiculously easy it is to integrate MailAPI.dev into your Next.js application. We'll go from zero to sending emails in under 5 minutes.
Installation
npm install mailapidev
Configuration
Grab your API key from your MailAPI.dev dashboard and add it to your environment variables:
# .env.local
MAILAPI_KEY=mapi_your_api_key_here
Creating Your Email Action
In Next.js 14+, we can use Server Actions to handle email sending securely on the server side. Create a new file for your email actions:
// src/actions/emailAction.js
"use server";
import { MailApiDev } from "mailapidev";
const client = new MailApiDev(process.env.MAILAPI_KEY);
export async function sendTransactionalEmail(emailData) {
try {
const { data, error } = await client.emails.send(emailData);
if (error) {
console.error("Email error:", error);
return { success: false, error: error.message };
}
return { success: true, data };
} catch (err) {
console.error("Failed to send email:", err);
return { success: false, error: "Email sending failed" };
}
}
export async function updateContact(contactData) {
try {
const { data, error } = await client.emails.update(contactData);
if (error) {
console.error("Contact update error:", error);
return { success: false, error: error.message };
}
return { success: true, data };
} catch (err) {
console.error("Failed to update contact:", err);
return { success: false, error: "Contact update failed" };
}
}
Building a Contact Form
Now let’s create a simple contact form component that uses our email action:
"use client";
import { useState } from "react";
import { sendTransactionalEmail } from "@/actions/emailActions";
export default function ContactForm() {
const [formData, setFormData] = useState({
email: "",
subject: "",
message: ""
});
const [status, setStatus] = useState("");
const [response, setResponse] = useState("");
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
setStatus("");
setResponse("");
};
const handleSubmit = async (e) => {
e.preventDefault();
setStatus("sending");
setResponse("");
const result = await sendTransactionalEmail({
from: "Contact Form <noreply@mail.mailapi.dev>",
to: formData.email,
subject: formData.subject,
message: formData.message,
});
if (result.success) {
setStatus("success");
setResponse("Your message was sent successfully!");
setFormData({ email: "", subject: "", message: "" });
} else {
setStatus("error");
setResponse(result.error || "Something went wrong. Please try again.");
}
};
return (
<div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-lg">
<h2 className="text-2xl font-bold mb-4">Get In Touch</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<input
type="email"
name="email"
placeholder="Your email address"
value={formData.email}
onChange={handleChange}
required
className="w-full px-4 py-2 border rounded-lg"
/>
</div>
<div>
<input
type="text"
name="subject"
placeholder="Subject"
value={formData.subject}
onChange={handleChange}
required
className="w-full px-4 py-2 border rounded-lg"
/>
</div>
<div>
<textarea
name="message"
placeholder="Your message"
value={formData.message}
onChange={handleChange}
required
rows="4"
className="w-full px-4 py-2 border rounded-lg"
/>
</div>
<button
type="submit"
disabled={status === "sending"}
className="w-full py-2 px-4 bg-orange-500 text-white rounded-lg hover:bg-orange-600 disabled:opacity-50"
>
{status === "sending" ? "Sending..." : "Send Message"}
</button>
{response && (
<p className={`text-center ${status === "success" ? "text-green-600" : "text-red-600"}`}>
{status === "success" ? "✅" : "❌"} {response}
</p>
)}
</form>
</div>
);
}
Using Email Templates
Want to send beautiful, pre-designed emails? MailAPI.dev makes it incredibly simple with templates:
First go to your mailapi dashboard to create a template. Then get the template id and template data variables.

"use client";
import { useState } from "react";
import { sendTransactionalEmail } from "@/actions/emailActions";
export default function WelcomeEmail() {
const [email, setEmail] = useState("");
const [status, setStatus] = useState("");
const sendWelcome = async (e) => {
e.preventDefault();
setStatus("sending");
const result = await sendTransactionalEmail({
from: "MailAPI <noreply@mail.mailapi.dev>",
to: email,
subject: "Welcome to MailAPI.dev!",
template_id: "welcome",
template_data: {
name: "John Doe",
url: "https://app.mailapi.dev/login"
},
verify_and_save: true // Automatically verify and save to contacts
});
if (result.success) {
setStatus("success");
setEmail("");
} else {
setStatus("error");
}
};
return (
<div className="max-w-md mx-auto p-6">
<h2 className="text-2xl font-bold mb-4">Send Welcome Email</h2>
<form onSubmit={sendWelcome} className="space-y-4">
<input
type="email"
placeholder="Enter email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-4 py-2 border rounded-lg"
/>
<button
type="submit"
disabled={status === "sending"}
className="w-full py-2 px-4 bg-orange-500 text-white rounded-lg"
>
{status === "sending" ? "Sending..." : "Send Welcome Email"}
</button>
</form>
</div>
);
}
Managing Your Email List
MailAPI.dev isn’t just about sending emails — it’s also a powerful Email List management system. You can update contact information whenever important events happen in your app.
import { updateContact } from "@/actions/emailActions";
async function trackUserLogin(userEmail) {
await updateContact({
email: userEmail,
lastSeenAt: new Date().toISOString()
});
}
Track/Update Subscription Events
When a user subscribes to your service:
import { updateContact } from "@/actions/emailActions";
async function handleNewSubscription(userEmail, planDetails) {
const result = await updateContact({
email: userEmail,
subscriptionStatus: "active",
plan: {
id: planDetails.priceId,
name: planDetails.planName,
amount: planDetails.amount,
interval: planDetails.interval
},
convertedAt: new Date().toISOString()
});
if (result.success) {
console.log("Subscriber added to contact list!");
}
}
Track Subscription Cancellations / Churn
When a user cancels their subscription:
import { updateContact } from "@/actions/emailActions";
async function handleCancellation(userEmail, reason) {
await updateContact({
email: userEmail,
subscriptionStatus: "canceled",
churnedAt: new Date().toISOString(),
churnReason: reason || "No reason provided",
lastSeenAt: new Date().toISOString()
});
}
Using MailAPI.dev with Node.js
Not using Next.js? No problem! MailAPI.dev works great with any Node.js application:
const { MailApiDev } = require('mailapidev');
const mailapi = new MailApiDev(process.env.MAILAPI_KEY);
async function sendEmail() {
const { data, error } = await mailapi.emails.send({
from: 'Your App <noreply@mail.mailapi.dev>',
to: 'user@example.com',
subject: 'Hello from Node.js!',
message: 'This is a test email sent from a Node.js application.'
});
if (error) {
console.error('Error:', error);
} else {
console.log('Success:', data);
}
}
sendEmail();
Get Started Today
Ready to simplify your email infrastructure? Here’s how to get started:
Sign up for a free account at MailAPI.dev
Install the NPM package:
npm install mailapidevGrab your API key from the dashboard
Start sending emails in minutes
Check out the complete documentation for advanced features like email automation, custom templates, and webhook integrations.
What are you building? Let me know in the comments how you’re using MailAPI.dev in your projects!
#



