Mailgun Setup
Learn how to set up Mailgun for reliable email delivery
Setting Up Mailgun ๐ง
This guide will help you set up Mailgun for reliable email delivery in your application.
Prerequisites ๐
- A Mailgun account
- Access to your domain's DNS settings
- Domain verified in Mailgun
- API key with sending permissions
Domain Verification ๐
- Go to Mailgun Dashboard
- Navigate to Sending > Domains > Add New Domain
- Follow the DNS verification steps
- Add the provided DNS records (SPF, DKIM, DMARC) to your domain
Implementation ๐ป
Install required dependencies:
pnpm add form-data mailgun.js
Create src/lib/email/sendMail.ts
:
import formData from "form-data";
import Mailgun from "mailgun.js";
import { appConfig } from "../config";
const sendMail = async (to: string, subject: string, html: string) => {
if (process.env.NODE_ENV !== "production") {
console.log(
"Sending email to",
to,
"with subject",
subject,
"and html",
html
);
return;
}
const mailgun = new Mailgun(formData);
const client = mailgun.client({
username: "api",
key: process.env.MAILGUN_API_KEY!,
});
const response = await client.messages.create(
process.env.MAILGUN_DOMAIN!,
{
from: `${appConfig.email.senderName} <${appConfig.email.senderEmail}>`,
to: [to],
subject: subject,
html: html,
"h:Reply-To": appConfig.email.senderEmail,
}
);
console.log("Email sent successfully", response);
};
export default sendMail;
Environment Variables ๐
Add these to your .env.local
:
MAILGUN_API_KEY=your_api_key
MAILGUN_DOMAIN=your_verified_domain
Testing Email Setup ๐งช
- Send a test email using Mailgun dashboard
- Monitor delivery in Mailgun logs
- Check email headers for proper authentication
- Use the Mailgun Email Test feature
Important Notes โ ๏ธ
- DNS propagation takes time (24-48 hours)
- Start with sandbox domain for testing
- Monitor email reputation in Mailgun dashboard
- Keep bounce rate below 5%
- Use production API key in production
Remember to wait for DNS propagation before testing your email setup. Rushing this process can lead to delivery issues! ๐