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 ๐Ÿ“‹

  1. A Mailgun account
  2. Access to your domain's DNS settings
  3. Domain verified in Mailgun
  4. API key with sending permissions

Domain Verification ๐Ÿ”

  1. Go to Mailgun Dashboard
  2. Navigate to Sending > Domains > Add New Domain
  3. Follow the DNS verification steps
  4. 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 ๐Ÿงช

  1. Send a test email using Mailgun dashboard
  2. Monitor delivery in Mailgun logs
  3. Check email headers for proper authentication
  4. Use the Mailgun Email Test feature

Important Notes โš ๏ธ

  1. DNS propagation takes time (24-48 hours)
  2. Start with sandbox domain for testing
  3. Monitor email reputation in Mailgun dashboard
  4. Keep bounce rate below 5%
  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! ๐Ÿš€