Email
Mailgun
Setting up Mailgun as your email provider.
Setup
- Create an account at mailgun.com
- Add and verify your domain
- Create an API key
- Set environment variables:
NEXT_PUBLIC_EMAIL_SERVICE="mailgun"
NEXT_MAILGUN_API_KEY=""
NEXT_MAILGUN_DOMAIN="mg.yourdomain.com"
NEXT_MAILGUN_FROM_EMAIL="noreply@yourdomain.com"How it works
The Mailgun provider in lib/services/email-service.ts:
function createMailgunProvider(): EmailProvider {
const domain = process.env.NEXT_MAILGUN_DOMAIN;
const fromEmail = process.env.NEXT_MAILGUN_FROM_EMAIL;
return {
async send({ to, subject, html, text, replyTo }) {
const FormData = (await import("form-data")).default;
const Mailgun = (await import("mailgun.js")).default;
const mailgun = new Mailgun(FormData);
const mg = mailgun.client({
username: "api",
key: process.env.NEXT_MAILGUN_API_KEY!,
});
const result = await mg.messages.create(domain, {
from: `${APP_NAME} <${fromEmail}>`,
to: [to],
subject,
html,
text,
...(replyTo && { "h:Reply-To": replyTo }),
});
return { success: true, messageId: result.id };
},
};
}Like Resend, the Mailgun SDK is dynamically imported.
Reply-To support
Mailgun uses the h:Reply-To header for reply-to addresses:
...(replyTo && { "h:Reply-To": replyTo }),This is used by the contact form to let you reply directly to the person who submitted the form.
Testing
Mailgun provides a sandbox domain for testing. You'll need to add authorized recipients in the sandbox settings before sending test emails.