useSend
Send email through useSend
useSend plugin for Medusa
Send Medusa email notifications through useSend, the open-source email platform formerly called Unsend. Write your emails as React components, and the plugin renders and sends them.
- Features
- Compatibility
- Installation
- Quick start
- Configuration
- Email templates
- Sending emails
- Attachments
- Testing without sending
- Delivery webhooks
- Contacts
- Admin page
- Migrating from @rokmohar/medusa-plugin-unsend
- Self-hosting useSend
- Changelog
- Contributing
- Security
- License
Features
- Notification provider for Medusa's notification module, on the Copy to clipboard
emailchannel. - React email templates, loaded from a folder and rendered to HTML and plain text with your app's own React.
- Translated templates: Copy to clipboard
OrderPlaced.sl.tsxis picked for Slovenian customers. - useSend dashboard templates, sent by id with variables.
- Per-email options: reply-to, CC, BCC, headers and scheduled sending.
- Attachments from Medusa's Copy to clipboard
createNotificationscall. - Safe retries: temporary failures are retried with backoff, and an idempotency key keeps a retry from sending the email twice.
- Mailpit, dry run and redirect modes for development and staging.
- Delivery webhooks: bounces, complaints, opens and clicks become Medusa events.
- Contacts: add newsletter subscribers to a useSend contact book.
- Admin page to preview templates and send yourself a test.
- Rate limiting per minute, and per-environment overrides of any option.
- Works with useSend Cloud and self-hosted useSend.
Compatibility
Plugin Medusa Copy to clipboard@rokmohar/medusa-plugin-usesend 2.3.x 2.23 or newer Copy to clipboard@rokmohar/medusa-plugin-usesend 2.0–2.2 2.22 Copy to clipboard@rokmohar/medusa-plugin-unsend 1.1.x 2.19 – 2.21 Copy to clipboard@rokmohar/medusa-plugin-unsend 1.0.8 2.4 – 2.18 Copy to clipboard@rokmohar/medusa-plugin-unsend 0.2.4 2.3.1 and older
Node.js 22.22 or newer is required, the same as Medusa 2.23.
Installation
1npm install @rokmohar/medusa-plugin-usesend
Or with Yarn:
1yarn add @rokmohar/medusa-plugin-usesend
Quick start
- Add your useSend credentials to Copy to clipboard
.env:
1234USESEND_API_KEY=us_...USESEND_FROM=Shop <no-reply@example.com># Only for self-hosted useSend; useSend Cloud is the defaultUSESEND_URL=
- Register the plugin and the notification provider in Copy to clipboard
medusa-config.ts:
1234567891011121314151617181920import { defineConfig, loadEnv } from '@medusajs/framework/utils'import type { UseSendEmailOptions } from '@rokmohar/medusa-plugin-usesend'loadEnv(process.env.NODE_ENV || 'development', process.cwd())module.exports = defineConfig({// ... other configplugins: [{resolve: '@rokmohar/medusa-plugin-usesend',options: {url: process.env.USESEND_URL,api_key: process.env.USESEND_API_KEY ?? '',from: process.env.USESEND_FROM ?? '',} satisfies UseSendEmailOptions,},],modules: [{resolve: '@medusajs/medusa/notification',
- Add a template to Copy to clipboard
src/templates/emails(see Email templates) and send it from a subscriber or workflow (see Sending emails).
The provider path is also exported as a constant, if you prefer it over the string:
12345678import { USESEND_PROVIDER_PATH } from '@rokmohar/medusa-plugin-usesend'// ...{resolve: USESEND_PROVIDER_PATH,id: 'usesend',options: { channels: ['email'] },}
Configuration
Option Type Default Description Copy to clipboardapi_key Copy to clipboardstring required useSend API key. Not needed with Copy to clipboardmailpitUrl or Copy to clipboarddryRun. Copy to clipboardfrom Copy to clipboardstring required Default sender, e.g. Copy to clipboardShop <no-reply@example.com>. Copy to clipboardurl Copy to clipboardstring Copy to clipboardhttps://app.usesend.com API URL. Set it to your instance's URL when you self-host useSend. Copy to clipboardtemplateDir Copy to clipboardstring Copy to clipboard<cwd>/src/templates/emails Folder the email templates are loaded from. Copy to clipboardretry.maxAttempts Copy to clipboardnumber Copy to clipboard3 Attempts per email, including the first one. Copy to clipboardretry.delay Copy to clipboardnumber Copy to clipboard1000 Delay before the first retry in ms. Copy to clipboardretry.backoff Copy to clipboardstring Copy to clipboard'exponential' Copy to clipboard'exponential' doubles the delay on every retry, Copy to clipboard'linear' adds it. Copy to clipboardrateLimit.maxPerMinute Copy to clipboardnumber Copy to clipboard60 Maximum emails sent per minute. Further emails wait. Copy to clipboarddefaultLocale Copy to clipboardstring none Locale used when a notification has none, see Locales. Copy to clipboarddryRun Copy to clipboardboolean Copy to clipboardfalse Log emails instead of sending them. Copy to clipboardmailpitUrl Copy to clipboardstring none Send every email to this Mailpit instead, see below. Copy to clipboardredirectTo Copy to clipboardstring none Send every email to this address instead. Copy to clipboardwebhook_secret Copy to clipboardstring none Signing secret that turns on delivery webhooks. Copy to clipboardcontacts.contactBookId Copy to clipboardstring none Default contact book for contacts. Copy to clipboardenvironment Copy to clipboardobject none Overrides of any option above per Copy to clipboardNODE_ENV, see below.
The options are validated at startup, and an invalid configuration stops the server with a message listing every problem.
Per-environment overrides
Copy to clipboardenvironment takes Copy to clipboarddevelopment, Copy to clipboardstaging and Copy to clipboardproduction keys. The overrides of the current Copy to clipboardNODE_ENV are merged over the top-level options:
12345678910111213options: {api_key: process.env.USESEND_API_KEY ?? '',from: 'Shop <no-reply@example.com>',environment: {development: {from: 'Shop (dev) <dev@example.com>',rateLimit: { maxPerMinute: 10 },},production: {retry: { maxAttempts: 5, delay: 2000 },},},}
Email templates
At startup the plugin loads every Copy to clipboard.tsx and Copy to clipboard.js file in the template folder. Each file's default export is a React component that receives the notification's Copy to clipboarddata as props:
123456789101112131415161718// src/templates/emails/OrderPlaced.tsxtype Props = {display_id: numbercustomer_name: string}const OrderPlaced = ({ display_id, customer_name }: Props) => {return (<div><h1>Thanks for your order, {customer_name}!</h1><p>Your order #{display_id} has been received.</p></div>)}OrderPlaced.Subject = 'Your order has been received'export default OrderPlaced
- The template name is the file name in kebab case: Copy to clipboard
OrderPlaced.tsxbecomes Copy to clipboardorder-placed. - Templates are rendered to HTML with your app's Copy to clipboard
reactand Copy to clipboardreact-dom, so they work with React Email components. - In production, Medusa compiles the templates to Copy to clipboard
.jsin Copy to clipboard.medusa/server/src/templates/emails, and the plugin loads those.
Subject
The subject is taken from the first of these that is set:
- Copy to clipboard
content.subjectin the Copy to clipboardcreateNotificationscall - Copy to clipboard
subjectin the template's metadata file - The component's static Copy to clipboard
Subjectproperty - The template name, e.g. Copy to clipboard
order-placed
Metadata file
A JSON file with the same name next to the template is optional:
12345678// src/templates/emails/OrderPlaced.json{"version": "1.0.0","subject": "Your order has been received","description": "Sent to the customer after checkout","tags": ["order", "customer"],"category": "orders"}
Locales
Add a locale to the file name for a translated variant: Copy to clipboardOrderPlaced.sl.tsx is the Slovenian Copy to clipboardorder-placed, and Copy to clipboardOrderPlaced.sl.json holds its metadata, on top of Copy to clipboardOrderPlaced.json.
The locale is read from Copy to clipboardprovider_data.locale, or else Copy to clipboarddata.locale, of the notification. The plugin uses the first variant that exists:
- The exact locale, e.g. Copy to clipboard
sl-si - Its language, e.g. Copy to clipboard
sl - The Copy to clipboard
defaultLocaleoption - The template without a locale
Preview data
The admin page fills a template with sample data. Set it as a static Copy to clipboardPreviewProps on the component, the same as React Email does, or as Copy to clipboardpreviewProps in the metadata file:
1234OrderPlaced.PreviewProps = {display_id: 1001,customer_name: 'Ana',}
A broken template doesn't keep the others from loading: the plugin logs which file failed and why.
Sending emails
Send an email through Medusa's notification module, with the template name and the data for its props:
1234567891011121314151617181920// src/subscribers/order-placed.tsimport type { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'import { Modules } from '@medusajs/framework/utils'export default async function orderPlacedHandler({ event: { data }, container }: SubscriberArgs<{ id: string }>) {const query = container.resolve('query')const notificationModuleService = container.resolve(Modules.NOTIFICATION)const {data: [order],} = await query.graph({entity: 'order',fields: ['display_id', 'email', 'shipping_address.first_name'],filters: { id: data.id },})await notificationModuleService.createNotifications({to: order.email,channel: 'email',template: 'order-placed',
Every email has an HTML and a plain-text part. The Copy to clipboardcontent of the notification overrides the template: Copy to clipboardcontent.html and Copy to clipboardcontent.text replace what the template renders, and an email with Copy to clipboardcontent.subject and Copy to clipboardcontent.html needs no template at all.
Per-email options
Pass options for one email in Copy to clipboardprovider_data:
12345678910111213await notificationModuleService.createNotifications({to: order.email,channel: 'email',template: 'order-placed',data: { display_id: order.display_id },provider_data: {replyTo: 'support@example.com',bcc: 'orders@example.com',headers: { 'X-Entity-Ref-ID': order.id },scheduledAt: '2026-11-01T09:00:00Z',locale: 'sl',},})
Copy to clipboardreplyTo, Copy to clipboardcc and Copy to clipboardbcc take an address or a list of addresses. Invalid Copy to clipboardprovider_data fails the notification without sending it.
useSend dashboard templates
To send a template you edit in the useSend dashboard instead of a file, pass its id and variables. Nothing is rendered locally, and the subject comes from the useSend template unless Copy to clipboardcontent.subject is set:
123456789await notificationModuleService.createNotifications({to: customer.email,channel: 'email',template: 'welcome',provider_data: {templateId: 'tmpl_123',variables: { firstName: customer.first_name },},})
The Copy to clipboardusesend service
The plugin's service is registered in the container as Copy to clipboardusesend. Use it to register templates in code instead of files, or to check that a template exists:
12345678import type { UseSendService } from '@rokmohar/medusa-plugin-usesend'const usesend = container.resolve<UseSendService>('usesend')usesend.addTemplate('welcome', {subject: 'Welcome!',content: { html: '<p>Welcome to our shop.</p>' },})
Attachments
Pass attachments in the Copy to clipboardattachments field of Copy to clipboardcreateNotifications. Each one needs a Copy to clipboardfilename and base64-encoded Copy to clipboardcontent:
1234567891011await notificationModuleService.createNotifications({to: 'customer@example.com',channel: 'email',template: 'invoice',attachments: [{filename: 'invoice-42.pdf',content: pdfBuffer.toString('base64'),},],})
useSend only accepts Copy to clipboardfilename and Copy to clipboardcontent, so other fields of Medusa's attachment (Copy to clipboardcontent_type, Copy to clipboarddisposition, Copy to clipboardid) are ignored. Attachments in Copy to clipboarddata.attachments are still read, for older code.
Testing without sending
Three options keep test emails away from real customers. All of them can be set per environment:
- Copy to clipboard
mailpitUrl: 'http://localhost:8025'sends every email to Mailpit, a local inbox, see below. - Copy to clipboard
dryRun: truelogs each email (recipient, subject and template) instead of sending it. - Copy to clipboard
redirectTo: 'dev@example.com'sends every email to one address. The original recipients go into an Copy to clipboardX-Original-Toheader, and CC and BCC are dropped.
12345678options: {api_key: process.env.USESEND_API_KEY ?? '',from: 'Shop <no-reply@example.com>',environment: {development: { dryRun: true },staging: { redirectTo: 'qa@example.com' },},}
Mailpit
Mailpit catches the emails in a web inbox, where you can read the HTML and plain text and open the attachments. Run it next to your database, e.g. in Copy to clipboarddocker-compose.yml:
12345services:mailpit:image: axllent/mailpit:latestports:- '127.0.0.1:8025:8025'
Then set Copy to clipboardmailpitUrl for local development. The plugin sends through Mailpit's HTTP API, so no useSend API key is needed, and the inbox is at Copy to clipboardhttp://localhost:8025:
12345options: {api_key: process.env.USESEND_API_KEY,from: 'Shop <no-reply@example.com>',mailpitUrl: process.env.MAILPIT_URL, // http://localhost:8025 in your local .env}
Each email is tagged with its template name. A useSend dashboard template can't be rendered locally, so it arrives as text with the template id and variables.
Keep a local Mailpit bound to localhost, because it accepts email from anyone who can reach it. To use a Mailpit on a server, for example for staging, protect it with logins: Copy to clipboardMP_UI_AUTH_FILE for the inbox, and Copy to clipboardMP_SEND_API_AUTH for a login that can only send. Then put the send login in the URL:
1MAILPIT_URL=https://sender:s3cret%24pass@mailpit.example.com
The plugin sends it as a Basic auth header, and the admin page shows the URL without it. Percent-encode special characters in the login: Medusa's Copy to clipboardloadEnv expands Copy to clipboard$, so write Copy to clipboard$ as Copy to clipboard%24.
Delivery webhooks
The plugin turns useSend webhook calls into Medusa events, so you can react to bounces, complaints, opens and clicks.
- In the useSend dashboard, add a webhook pointing at Copy to clipboard
https://<your-medusa>/hooks/usesendand copy its signing secret. - Set the Copy to clipboard
webhook_secretoption to it. Without it, the route responds 404.
Every call is verified and emitted as Copy to clipboardusesend.<type>, e.g. Copy to clipboardusesend.email.bounced. The event names are exported as Copy to clipboardUSESEND_WEBHOOK_EVENTS:
12345678910111213// src/subscribers/email-bounced.tsimport type { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'import { USESEND_WEBHOOK_EVENTS, type UseSendWebhookEventData } from '@rokmohar/medusa-plugin-usesend'export default async function emailBounced({ event, container }: SubscriberArgs<UseSendWebhookEventData>) {const { notification_id, to, data } = event.datacontainer.resolve('logger').warn(`Email ${notification_id} to ${to.join(', ')} bounced: ${JSON.stringify(data)}`)}export const config: SubscriberConfig = {event: USESEND_WEBHOOK_EVENTS.EMAIL_BOUNCED,}
The event data holds Copy to clipboardcall_id, Copy to clipboardtype, Copy to clipboardemail_id, Copy to clipboardnotification_id (the Medusa notification that sent the email, when there is one), Copy to clipboardto, Copy to clipboardstatus and the raw useSend Copy to clipboarddata. useSend can deliver a call more than once, so use Copy to clipboardcall_id to skip duplicates.
Contacts
Add the people who sign up for your newsletter to a useSend contact book, so you can send them campaigns from useSend. The plugin doesn't sync customers on its own, because Medusa has no newsletter consent; call it from your own sign-up flow:
12345678const usesend = container.resolve<UseSendService>('usesend')await usesend.upsertContact({email: 'ana@example.com',firstName: 'Ana',subscribed: true,properties: { locale: 'sl' },})
Copy to clipboardupsertContact creates the contact, or updates the one with the same email, in the contact book of the Copy to clipboardcontacts.contactBookId option, or the one passed as the second argument. Copy to clipboardremoveContact(contactId) removes one.
Admin page
Settings → useSend in the Medusa admin lists the loaded templates and shows whether the plugin is live, in dry run or redirecting. For each template you can edit the sample data, pick a locale, preview the HTML and plain text, and send a test to yourself. Test emails go through the notification module, so they show up in the notification log and follow Copy to clipboarddryRun and Copy to clipboardredirectTo.
Migrating from @rokmohar/medusa-plugin-unsend
Unsend was renamed to useSend, and this plugin was renamed with it in 2.0.0. Your templates and options don't change.
- Swap the package:
12npm uninstall @rokmohar/medusa-plugin-unsendnpm install @rokmohar/medusa-plugin-usesend
- Rename in your code and Copy to clipboard
medusa-config.ts: 1.x (Copy to clipboard@rokmohar/medusa-plugin-unsend) 2.x (Copy to clipboard@rokmohar/medusa-plugin-usesend) Copy to clipboardresolve: '@rokmohar/medusa-plugin-unsend'Copy to clipboardresolve: '@rokmohar/medusa-plugin-usesend'Copy to clipboard'@rokmohar/medusa-plugin-unsend/providers/notification'Copy to clipboard'@rokmohar/medusa-plugin-usesend/providers/notification'Copy to clipboardUNSEND_PROVIDER_PATHCopy to clipboardUSESEND_PROVIDER_PATHCopy to clipboarddependencies: ['unsend']Copy to clipboarddependencies: ['usesend']Copy to clipboardcontainer.resolve('unsend')Copy to clipboardcontainer.resolve('usesend')Copy to clipboardUnsendServiceCopy to clipboardUseSendServiceCopy to clipboardUnsendEmailOptions, Copy to clipboardUnsendEmailTemplate, Copy to clipboardUnsendEmailAttachmentCopy to clipboardUseSendEmailOptions, Copy to clipboardUseSendEmailTemplate, Copy to clipboardUseSendEmailAttachment - Optionally rename the provider Copy to clipboard
idfrom Copy to clipboardunsendto Copy to clipboardusesend. Medusa stores the provider id on each sent notification, so keep Copy to clipboardunsendif you rely on filtering past notifications by provider. - Optionally rename your Copy to clipboard
UNSEND_*environment variables to Copy to clipboardUSESEND_*. The plugin only reads the values you pass in its options.
Self-hosting useSend
useSend can run on your own server; it needs PostgreSQL, Redis and AWS SES. Follow the self-hosting guide, then set Copy to clipboardurl to your instance, e.g. Copy to clipboardhttp://localhost:3000.
Changelog
See CHANGELOG.md and the GitHub releases.
Contributing
Bug reports, documentation fixes and pull requests are welcome. See CONTRIBUTING.md for the development setup and the code of conduct.
Security
Please report vulnerabilities privately, as described in SECURITY.md.
License
MIT © Rok Mohar
