Framework Adapters
Drop-in adapters for every major backend framework. Install the package, configure once, send from anywhere in your app.
Each adapter wraps the Mailgrid REST API and plugs into your framework's native mail/plugin system. Set MAILGRID_API_KEY in your environment and swap in the backend — no other code changes needed.
Next.js
Package: packages/adapter-nextjs. Works with both the App Router (Route Handlers, Server Actions) and Pages Router API routes. Zero dependencies beyond the Mailgrid core.
Install
npm install @mailgrid/nextjs
Configure
MAILGRID_API_KEY=mb_live_xxxxxxxxxxxx
Route Handler (App Router)
import { mailgrid } from '@mailgrid/nextjs'; import { NextResponse } from 'next/server'; const mg = mailgrid({ apiKey: process.env.MAILGRID_API_KEY! }); export async function POST(req: Request) { const { to, subject, html } = await req.json(); const result = await mg.emails.send({ from: 'hello@yourdomain.com', to, subject, html, }); return NextResponse.json(result); }
Server Action (App Router)
'use server'; import { mailgrid } from '@mailgrid/nextjs'; const mg = mailgrid({ apiKey: process.env.MAILGRID_API_KEY! }); export async function sendWelcomeEmail(email: string) { return mg.emails.send({ from: 'welcome@yourdomain.com', to: email, subject: 'Welcome aboard', html: '<p>Thanks for signing up.</p>', }); }
NestJS
Package: packages/adapter-nestjs. Registers a MailgridModule and exposes a MailgridService for injection anywhere in your module tree.
Install
npm install @mailgrid/nestjs
Register module
import { Module } from '@nestjs/common'; import { MailgridModule } from '@mailgrid/nestjs'; @Module({ imports: [ MailgridModule.forRoot({ apiKey: process.env.MAILGRID_API_KEY!, defaults: { from: 'noreply@yourdomain.com' }, }), ], }) export class AppModule {}
Inject and send
import { Injectable } from '@nestjs/common'; import { MailgridService } from '@mailgrid/nestjs'; @Injectable() export class AuthService { constructor(private readonly mail: MailgridService) {} async sendPasswordReset(email: string, token: string) { return this.mail.send({ to: email, subject: 'Reset your password', html: `<a href="https://app.example.com/reset?t=${token}">Reset</a>`, }); } }
Use MailgridModule.forRootAsync() with useFactory when you need to inject a ConfigService.
Django
Package: packages/adapter-django (PyPI: mailgrid-django). Implements Django's BaseEmailBackend so every call to send_mail(), EmailMessage, or EmailMultiAlternatives routes through Mailgrid automatically.
Install
pip install mailgrid-django
Configure
EMAIL_BACKEND = 'mailgrid_django.backend.MailgridBackend' MAILGRID_API_KEY = env('MAILGRID_API_KEY') DEFAULT_FROM_EMAIL = 'noreply@yourdomain.com'
Send
from django.core.mail import send_mail, EmailMultiAlternatives # Plain send_mail — works as-is send_mail( subject='Welcome', message='Thanks for joining.', from_email='welcome@yourdomain.com', recipient_list=['user@example.com'], ) # HTML + plain-text alternative msg = EmailMultiAlternatives( subject='Order confirmed', body='Your order #1234 has shipped.', from_email='orders@yourdomain.com', to=['customer@example.com'], ) msg.attach_alternative('<p>Your order <strong>#1234</strong> has shipped.</p>', 'text/html') msg.send()
FastAPI
Package: packages/adapter-fastapi (PyPI: mailgrid-fastapi). Provides an APIRouter you can mount, plus a MailgridClient dependency for use anywhere in your route handlers.
Install
pip install mailgrid-fastapi
Configure and mount
from fastapi import FastAPI from mailgrid_fastapi import MailgridClient, mailgrid_router import os app = FastAPI() app.include_router(mailgrid_router, prefix='/mail') # Dependency factory def get_mail() -> MailgridClient: return MailgridClient(api_key=os.environ['MAILGRID_API_KEY'])
Use in a route
from fastapi import APIRouter, Depends from mailgrid_fastapi import MailgridClient from main import get_mail router = APIRouter() @router.post('/signup') async def signup(email: str, mail: MailgridClient = Depends(get_mail)): await mail.send( to=email, subject='Verify your email', html='<p>Click to verify.</p>', from_email='auth@yourdomain.com', ) return {'ok': True}
Flask
Package: packages/adapter-flask (PyPI: mailgrid-flask). Registers a Flask Blueprint and exposes a current_mailgrid application-context proxy, similar to Flask-Mail.
Install
pip install mailgrid-flask
Configure
from flask import Flask from mailgrid_flask import Mailgrid app = Flask(__name__) app.config['MAILGRID_API_KEY'] = 'mb_live_xxxxxxxxxxxx' app.config['MAILGRID_DEFAULT_FROM'] = 'noreply@yourdomain.com' mail = Mailgrid(app)
Send from a Blueprint route
from flask import Blueprint, request, jsonify from mailgrid_flask import current_mailgrid auth_bp = Blueprint('auth', __name__) @auth_bp.post('/register') def register(): data = request.get_json() current_mailgrid.send( to=data['email'], subject='Welcome to the app', html='<p>You are now registered.</p>', ) return jsonify(ok=True)
Ruby on Rails
Package: packages/adapter-rails (RubyGems: mailgrid-rails). Implements an ActionMailer delivery method — drop it in and every existing ApplicationMailer subclass starts routing through Mailgrid.
Install
bundle add mailgrid-rails
Configure
config.action_mailer.delivery_method = :mailgrid config.action_mailer.mailgrid_settings = { api_key: ENV['MAILGRID_API_KEY'], default_from: 'noreply@yourdomain.com' }
Mailer (unchanged)
class UserMailer < ApplicationMailer def welcome_email(user) @user = user mail( to: user.email, subject: 'Welcome to the app' ) end end # Deliver as usual — routing handled by the adapter UserMailer.welcome_email(@user).deliver_later
Laravel
Package: packages/adapter-laravel (Packagist: mailgrid/laravel). Implements Symfony's AbstractTransport and registers a mailgrid mailer driver. Compatible with Laravel 10+.
Install
composer require mailgrid/laravel
Configure
'mailgrid' => [ 'transport' => 'mailgrid', 'api_key' => env('MAILGRID_API_KEY'), ],
MAIL_MAILER=mailgrid MAILGRID_API_KEY=mb_live_xxxxxxxxxxxx MAIL_FROM_ADDRESS=noreply@yourdomain.com
Send
use Illuminate\Support\Facades\Mail; use App\Mail\WelcomeMail; Mail::to('user@example.com')->send(new WelcomeMail());
Spring Boot
Package: packages/adapter-spring (Maven: space.mailgrid:mailgrid-spring-boot-starter). Auto-configures a MailgridMailSender bean when MAILGRID_API_KEY is present in the environment. Annotation-driven via @EnableMailgrid.
Install
<dependency> <groupId>space.mailgrid</groupId> <artifactId>mailgrid-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency>
Configure
mailgrid.api-key=mb_live_xxxxxxxxxxxx mailgrid.default-from=noreply@yourdomain.com
Enable and inject
@SpringBootApplication @EnableMailgrid public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Service public class NotificationService { @Autowired private MailgridMailSender mailSender; public void sendWelcome(String to) { SimpleMailMessage msg = new SimpleMailMessage(); msg.setTo(to); msg.setSubject("Welcome aboard"); msg.setText("Thanks for signing up."); mailSender.send(msg); } }
Phoenix / Elixir
Package: packages/adapter-phoenix (Hex: mailgrid_swoosh). Implements the Swoosh Adapter behaviour so you can use any existing Swoosh-based mailer module without changes.
Install
{:mailgrid_swoosh, "~> 1.0"}
Configure
config :my_app, MyApp.Mailer,
adapter: Swoosh.Adapters.Mailgrid,
api_key: System.fetch_env!("MAILGRID_API_KEY")
Send
defmodule MyApp.UserEmail do import Swoosh.Email def welcome(user) do new() |> to({user.name, user.email}) |> from({"MyApp", "noreply@yourdomain.com"}) |> subject("Welcome to MyApp") |> html_body("<p>Hello #{user.name}, welcome aboard.</p>") end end # In a context or controller: MyApp.UserEmail.welcome(user) |> MyApp.Mailer.deliver()
Nuxt 3
Package: packages/adapter-nuxt (npm: @mailgrid/nuxt). Implements a defineNuxtModule that auto-imports a useMailgrid() server composable for use in server/ routes and API handlers.
Install
npm install @mailgrid/nuxt
Configure
export default defineNuxtConfig({ modules: ['@mailgrid/nuxt'], mailgrid: { apiKey: process.env.MAILGRID_API_KEY, defaultFrom: 'noreply@yourdomain.com', }, })
Server route
export default defineEventHandler(async (event) => { const { email, message } = await readBody(event); const mail = useMailgrid(); await mail.send({ to: email, subject: 'We received your message', html: `<p>${message}</p>`, }); return { ok: true }; })
SvelteKit
Package: packages/adapter-sveltekit (npm: @mailgrid/sveltekit). Provides a typed createMailgrid() factory for use inside +server.ts files and form actions.
Install
npm install @mailgrid/sveltekit
Configure
MAILGRID_API_KEY=mb_live_xxxxxxxxxxxx
Route handler
import { createMailgrid } from '@mailgrid/sveltekit'; import { MAILGRID_API_KEY } from '$env/static/private'; import { json } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; const mail = createMailgrid({ apiKey: MAILGRID_API_KEY }); export const POST: RequestHandler = async ({ request }) => { const { to, subject, html } = await request.json(); const result = await mail.send({ to, subject, html, from: 'hello@yourdomain.com' }); return json(result); };
Remix
Package: packages/adapter-remix (npm: @mailgrid/remix). Exports createMailgridAction and createMailgridLoader helper factories that wrap your Remix action/loader with a pre-configured client.
Install
npm install @mailgrid/remix
Configure
import { createMailgridClient } from '@mailgrid/remix'; export const mail = createMailgridClient({ apiKey: process.env.MAILGRID_API_KEY!, defaultFrom: 'noreply@yourdomain.com', });
Use in an action
import { json } from '@remix-run/node'; import { mail } from '~/services/mail.server'; import type { ActionFunctionArgs } from '@remix-run/node'; export async function action({ request }: ActionFunctionArgs) { const form = await request.formData(); await mail.send({ to: String(form.get('email')), subject: 'Thanks for reaching out', html: '<p>We will reply within 24 hours.</p>', }); return json({ success: true }); }
Express
Package: packages/adapter-express (npm: @mailgrid/express). Exposes a middleware that attaches a req.mail client, plus an optional mounted router for webhook handling.
Install
npm install @mailgrid/express
Configure middleware
import express from 'express'; import { mailgridMiddleware } from '@mailgrid/express'; const app = express(); app.use(express.json()); app.use(mailgridMiddleware({ apiKey: process.env.MAILGRID_API_KEY!, defaultFrom: 'noreply@yourdomain.com', }));
Use in a route
import { Router } from 'express'; const router = Router(); router.post('/register', async (req, res) => { const { email } = req.body; await req.mail.send({ to: email, subject: 'Welcome', html: '<p>Account created.</p>', }); res.json({ ok: true }); }); export default router;
Fastify
Package: packages/adapter-fastify (npm: @mailgrid/fastify). Wraps the client in a fastify-plugin and decorates the fastify instance with a mail namespace.
Install
npm install @mailgrid/fastify
Register plugin
import Fastify from 'fastify'; import mailgridPlugin from '@mailgrid/fastify'; const app = Fastify(); await app.register(mailgridPlugin, { apiKey: process.env.MAILGRID_API_KEY!, defaultFrom: 'noreply@yourdomain.com', });
Use in a route
app.post('/notify', async (request, reply) => { const { to, subject, body } = request.body as { to: string; subject: string; body: string; }; const result = await app.mail.send({ to, subject, html: body }); return reply.send(result); });
Hono
Package: packages/adapter-hono (npm: @mailgrid/hono). Provides a MiddlewareHandler that sets the Mailgrid client on the Hono context, and a typed getMailgrid(c) helper.
Install
npm install @mailgrid/hono
Register middleware
import { Hono } from 'hono'; import { mailgrid, getMailgrid } from '@mailgrid/hono'; const app = new Hono(); app.use('*', mailgrid({ apiKey: process.env.MAILGRID_API_KEY!, defaultFrom: 'noreply@yourdomain.com', }));
Use in a handler
app.post('/invite', async (c) => { const { email } = await c.req.json(); const mail = getMailgrid(c); await mail.send({ to: email, subject: 'You have been invited', html: '<p>Click to accept your invitation.</p>', }); return c.json({ ok: true }); });
AdonisJS
Package: packages/adapter-adonisjs (npm: @mailgrid/adonisjs). Registers a mailgrid mail driver that integrates with the AdonisJS @adonisjs/mail package using its first-class driver API.
Install
npm install @mailgrid/adonisjs node ace configure @mailgrid/adonisjs
Configure
import { defineConfig } from '@adonisjs/mail'; import { mailgridDriver } from '@mailgrid/adonisjs'; import env from '#start/env'; export default defineConfig({ default: 'mailgrid', mailers: { mailgrid: mailgridDriver({ apiKey: env.get('MAILGRID_API_KEY'), defaultFrom: 'noreply@yourdomain.com', }), }, });
Send
import { BaseMail } from '@adonisjs/mail'; export default class WelcomeMail extends BaseMail { subject = 'Welcome to our platform'; prepare() { this.message .to('user@example.com') .htmlView('emails/welcome'); } } // Deliver from anywhere in the app import mail from '@adonisjs/mail/services/main'; await mail.send(new WelcomeMail());
Koa
Package: packages/adapter-koa (npm: @mailgrid/koa). Attaches a ctx.mail client via Koa middleware. Compatible with Koa 2+ and koa-router / @koa/router.
Install
npm install @mailgrid/koa
Register middleware
import Koa from 'koa'; import bodyParser from 'koa-bodyparser'; import { mailgridMiddleware } from '@mailgrid/koa'; const app = new Koa(); app.use(bodyParser()); app.use(mailgridMiddleware({ apiKey: process.env.MAILGRID_API_KEY!, defaultFrom: 'noreply@yourdomain.com', }));
Use in a router
import Router from '@koa/router'; const router = new Router(); router.post('/users', async (ctx) => { const { email } = ctx.request.body as { email: string }; await ctx.mail.send({ to: email, subject: 'Account created', html: '<p>Your account is ready.</p>', }); ctx.body = { ok: true }; }); export default router;
All framework adapters are designed for server-side use only. The MAILGRID_API_KEY environment variable must never be bundled into or sent to a browser. In Next.js, prefix server-only env vars without the NEXT_PUBLIC_ prefix. In SvelteKit, use $env/static/private.
What's next?
- Email API reference — full list of send options: attachments, headers, tags, stream routing
- Templates — use Handlebars templates or AI-generated HTML with any adapter
- Webhooks — handle delivery events in your framework's route handlers
- Multi-stream sending — separate transactional from marketing per adapter
- MCP server — drive Mailgrid from Claude or Cursor during development