• Сообщество
  • Блог
Документация
Плагины и интеграцииВсе расширения для Medusa от сообществаСтартерыЗапускайте проекты быстрее с готовыми решениями
ЭкспертыПодберите специалиста для разработки и развития вашего проекта на MedusaКейсыПосмотрите примеры Medusa в продакшене и успешные внедрения
Меч Moscow
Комплексная e-commerce платформа на Medusa для московского fashion-бренда

Меч Moscow · Fashion

Gorgo снижает затраты на адаптацию Medusa к локальным рынкам.

Мы разрабатываем плагины интеграции, осуществляем поддержку и развиваем сообщество разработчиков на Medusa в Telegram.

  • Ресурсы Medusa
  • Плагины и интеграции
  • Стартеры
  • Эксперты
  • Кейсы
  • Medusa Чат в Telegram
  • Medusa Новости в Telegram
  • Документация Gorgo
  • Связаться с нами
  • TelegramGitHub
Плагины
N

Notification mailgun

Mailgun notification provider plugin for MedusaJS v2

npm install @mdgar/medusa-notification-mailgun
Категория
Уведомления
Создано
Mdgar
Версия
0.3.0
Последнее обновление
3 месяца назад
Ежемесячные загрузки
Загрузка данных
Звезды на Github
0
npmNPMGitHubGithub

@mdgar/medusa-notification-mailgun

Mailgun notification provider plugin for MedusaJS v2.




Sends transactional emails via the Mailgun HTTP API. Supports stored templates (with localization), inline HTML/text, file attachments, and includes an Admin UI page for sending test emails and verifying event coverage.

Requires MedusaJS v2.3.0 or later.

In a hurry? Quickstart! From install to first email in ~15 minutes.

What this plugin provides

  • Notification provider — registers as a notification provider for the channel. Called automatically by Medusa when you use in a subscriber.
  • Admin API: send test email — . Sends a test email to a registered admin user.
  • Admin API: event checklist — . Scans your subscribers and Mailgun account to report coverage status for each tracked event.
  • Admin UI — a "Mailgun" page in the Medusa admin sidebar with two tabs: "Event Checklist" (default) and "Send Test".

Prerequisites

  • Node.js v20+
  • MedusaJS v2.3.0+
  • A Mailgun account with a verified sending domain

Installation

1pnpm add @mdgar/medusa-notification-mailgun
2# or
3npm install @mdgar/medusa-notification-mailgun
4# or
5yarn add @mdgar/medusa-notification-mailgun

is bundled as a direct dependency of the plugin and will be installed automatically; you do not need to install it separately.

Configuration

Add the plugin to . Two entries are needed: a entry to load the admin UI and API routes, and a entry to register the notification provider.

1import { defineConfig } from "@medusajs/framework/utils"
2
3module.exports = defineConfig({
4 // ...
5 plugins: [
6 "@mdgar/medusa-notification-mailgun",
7 ],
8 modules: [
9 {
10 resolve: "@medusajs/medusa/notification",
11 options: {
12 providers: [
13 {
14 resolve: "@mdgar/medusa-notification-mailgun/providers/notification-mailgun",
15 id: "mailgun",
16 options: {
17 channels: ["email"],
18 api_key: process.env.MAILGUN_API_KEY,
19 domain: process.env.MAILGUN_DOMAIN,
20 from: process.env.MAILGUN_FROM, // optional
21 region: "us", // optional, "us" | "eu"
22 },
23 },
24 ],
25 },
26 },
27 ],
28})

Options

OptionRequiredDefaultDescription
Yes—Your Mailgun API key
Yes—Your verified Mailgun sending domain
NoDefault sender address used when is not passed per-notification
NoMailgun API region: or
Nobuilt-in map — override or extend the checklist's event→template map without forking the plugin. Entries with an key that matches a built-in are replaced; new entries are appended.

Customizing the checklist event map

The admin "Event Checklist" tab scans your subscribers against a built-in list of Medusa events and their expected Mailgun template names (e.g. → ). To add your own events or rename an expected template, pass in the provider options:

1{
2 resolve: "@mdgar/medusa-notification-mailgun/providers/notification-mailgun",
3 id: "mailgun",
4 options: {
5 channels: ["email"],
6 api_key: process.env.MAILGUN_API_KEY,
7 domain: process.env.MAILGUN_DOMAIN,
8 eventMap: [
9 // Override a built-in: use a different template name for order.placed
10 { event: "order.placed", expected_template: "my-order-confirmation" },
11 // Append a custom event
12 { event: "loyalty.tier_upgraded", expected_template: "loyalty-upgrade" },
13 ],
14 },
15}

Each entry is . The checklist endpoint merges your overrides onto the built-in map by key.

Environment variables

VariableRequiredDescription
YesYour Mailgun API key
YesYour verified Mailgun sending domain
NoDefault sender address
NoSet to to use the EU API endpoint. Omit for US.

Set these in your file:

1MAILGUN_API_KEY=key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2MAILGUN_DOMAIN=mg.yourdomain.com
3MAILGUN_FROM=no-reply@yourdomain.com
4# MAILGUN_REGION=eu # uncomment if your account is on the EU region

Reference these in via — the checklist endpoint reads credentials from the same plugin options object, not from the environment directly.

Sending notifications

The provider integrates with Medusa's built-in notification system. Call from a subscriber or workflow:

1const notificationService = container.resolve(Modules.NOTIFICATION)
2
3await notificationService.createNotifications({
4 to: "customer@example.com",
5 channel: "email",
6 template: "order-confirmation",
7 data: {
8 subject: "Your order is confirmed",
9 order_id: "ord_123",
10 customer_name: "Alice",
11 },
12})

The payload

The object controls how the email is built and carries template variables. All values must be strings.

FieldTypeDescription
Email subject line. Optional — if omitted when using a stored template, Mailgun uses the subject defined in the template. Recommended when sending inline /.
Selects a Mailgun template version (e.g. , ). Only used when is set.
Inline HTML body. Used when no is set.
Plain-text body. Used when neither nor is set.
Per-notification sender address override. Takes precedence over the top-level field only when the top-level field is not set.
Sets the header on the outgoing message.
any otherAdditional keys are passed to Mailgun as template variables.

Content selection

The provider selects the message body using this priority order:

  1. — a Mailgun stored template; all fields are passed as .
  2. — raw HTML body (no template).
  3. — plain-text body.

If none of , , or is provided, the provider throws rather than sending an email with a serialized DTO body.

Use or when you want to generate content dynamically in code rather than maintain a template in the Mailgun dashboard.

Stored template

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 template: "order-confirmation",
5 data: {
6 subject: "Your order is confirmed",
7 order_id: "ord_123",
8 },
9})

Template variables are forwarded to Mailgun via and available as inside Mailgun's Handlebars templates.

Localized template

Create multiple versions of a template in the Mailgun dashboard, tagging each with a locale (e.g. , , ). Pass in to select the matching version:

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 template: "order-confirmation",
5 data: {
6 locale: "fr",
7 subject: "Votre commande est confirmée",
8 order_id: "ord_123",
9 },
10})

When is present, the plugin sets Mailgun's parameter. If omitted, Mailgun uses the template's default version.

Inline HTML

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 data: {
5 subject: "Welcome!",
6 html: "<h1>Welcome to our store</h1><p>Thanks for signing up.</p>",
7 },
8})

Plain text

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 data: {
5 subject: "Your receipt",
6 text: "Thanks for your order. Your total was $42.00.",
7 },
8})

Attachments

Pass base64-encoded file content in the field:

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 data: { subject: "Your invoice", text: "See attached." },
5 attachments: [
6 {
7 filename: "invoice.pdf",
8 content: "<base64-encoded content>",
9 },
10 ],
11} as any)

Overriding the sender address

Pass a field on the notification to override the plugin-level default for a single send:

1await notificationService.createNotifications({
2 to: "customer@example.com",
3 channel: "email",
4 from: "billing@yourdomain.com",
5 data: { subject: "Invoice", text: "..." },
6} as any)

is also accepted, but is ignored when the top-level notification field is set. Resolution order is: top-level → → plugin-level default → . The top-level field shown above is the preferred method.

Wiring up Medusa events to templates

Medusa fires events for commerce operations (order placed, shipment created, password reset, etc.) but sends no email by default. To send email on an event you need a Mailgun template and a subscriber that calls when the event fires.

See for the complete how-to guide: subscriber patterns for each event, the full event reference, and suggested template variables.

New to the plugin? The quickstart walks through the full setup end-to-end.

Admin UI

The plugin adds a Mailgun page to the Medusa admin sidebar (envelope icon). The route is .

The page has two tabs:

  • Event Checklist (default) — runs and displays per-event status as a table. Shows whether each tracked event has a subscriber, what template name was detected in the subscriber, and whether that template exists in Mailgun. For events with a confirmed Mailgun template, the template name is displayed below the event name in the table row.

  • Send Test — form to send a test email to a registered admin user. Fields: recipient (dropdown of admin users), subject, optional message body, optional template name, optional from-address override, optional reply-to address, and optional key-value template variables.

Admin API: send test email

1POST /admin/mailgun/send-email
2Authorization: Bearer <admin-jwt>
3Content-Type: application/json

Sends a test email through the Mailgun notification provider.

Request body

FieldTypeRequiredDescription
(email)YesRecipient address. Must be a registered admin user email.
NoEmail subject line. If omitted, Mailgun uses the template's own subject.
NoMailgun template name. If omitted, or is used for the body.
(email)NoSender address override. Defaults to the plugin's configured .
(email)NoReply-To address. When set, replies are directed to this address instead of the sender.
NoTemplate variables or body content. Typed as with additional keys allowed via passthrough (e.g. , ).

Constraint: must be the email address of a registered Medusa admin user. The endpoint looks up the address in the user service before sending. Arbitrary addresses are rejected.

If no template is specified and contains neither nor , the plugin sends a plain-text fallback: (or just if no subject is provided).

Response

{ "success": true, "notification_id": "noti_01..." }

Example

1curl -X POST https://yourstore.com/admin/mailgun/send-email \
2 -H "Authorization: Bearer <admin-jwt>" \
3 -H "Content-Type: application/json" \
4 -d '{
5 "to": "admin@yourstore.com",
6 "subject": "Hello from Mailgun",
7 "template": "welcome",
8 "data": { "customer_name": "Alice" }
9 }'

Admin API: event checklist

1GET /admin/mailgun/checklist
2Authorization: Bearer <admin-jwt>

Returns a diagnostic report for all tracked Medusa events. For each event, the endpoint checks:

  1. Whether a subscriber file exists in that references the event name.
  2. Whether that subscriber file contains a static string literal, and what its value is.
  3. Whether that template exists in your Mailgun account (requires and to be set in the plugin options in ).

Per-event status values:

StatusMeaning
Subscriber found, a static template name was detected in the file, and that template exists in Mailgun.
Subscriber found and a static template name was detected, but that template does not exist in Mailgun yet.
Subscriber found, but no static template name was detected. The subscriber may be using inline HTML or plain text.
No subscriber found for this event.

The top-level rolls up the worst result across all events, excluding . events do not cause a or rollup.

CI usage

1# Fail if any event is missing a subscriber or Mailgun template
2curl -sf -H "Authorization: Bearer $MEDUSA_ADMIN_TOKEN" \
3 "$MEDUSA_BACKEND_URL/admin/mailgun/checklist" \
4 | jq -e '.status == "pass"'
5
6# Fail only if a subscriber is missing; allow missing templates
7curl -sf -H "Authorization: Bearer $MEDUSA_ADMIN_TOKEN" \
8 "$MEDUSA_BACKEND_URL/admin/mailgun/checklist" \
9 | jq -e '.status != "fail"'

See for the full response shape, field descriptions, and additional CI patterns.

Development

1# Install dependencies
2pnpm install
3
4# Build the plugin
5pnpm run build
6
7# Start in watch/develop mode
8pnpm run dev
9
10# Run tests
11pnpm test

This plugin uses the official Medusa plugin toolchain ( / ).

Local development with pnpm link

To test the plugin in a local Medusa project before publishing:

1# In this plugin directory — build first, then link
2pnpm run build
3pnpm link --global
4
5# In your Medusa project
6pnpm link --global @mdgar/medusa-notification-mailgun

After any source change, run in the plugin directory again, or keep running to rebuild continuously.

Tests

The test suite uses Jest and ts-jest. Run with:

pnpm test

Coverage includes:

  • — rejects missing or
  • Template path — header, locale selection
  • Inline HTML and plain-text paths
  • Sender resolution — configured address vs. default
  • Subject omitted from payload when is absent (defers to template subject)
  • Base64 attachment decoding
  • Mailgun API errors are wrapped in with a sanitized, correlation-id'd message (); raw error details are logged server-side only. validation errors are re-thrown unwrapped.
  • EU region endpoint selection ()
  • Return value — field with field fallback

License

MIT

Еще в этой категории

Посмотреть все
Уведомления
Nodemailer logo

Nodemailer

От Perseides

Отправляйте email-уведомления через Nodemailer (SMTP)

Загрузка данных
npm
Уведомления
Mailgun logo

Mailgun

От Webbers

Отправляйте и управляйте уведомлениями по электронной почте

Загрузка данных
GitHubnpm
Уведомления
Postmark logo

Postmark

От Bram-hammer

Транзакционные письма через Postmark

Загрузка данных
GitHubnpm