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

Меч Moscow · Fashion

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

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

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

Unsend

Создавайте шаблоны писем с Unsend

npm install @rokmohar/medusa-plugin-unsend
Категория
Уведомления
Создано
Rokmohar
Версия
1.0.8
Последнее обновление
4 месяца назад
Ежемесячные загрузки
Загрузка данных
Звезды на Github
4
npmNPMGitHubGithub

Unsend plugin for MedusaJS v2

Installation

Run the following command to install the plugin with npm:

npm install --save @rokmohar/medusa-plugin-unsend

Or with yarn:

yarn add @rokmohar/medusa-plugin-unsend

⚠️ MedusaJS v2.4.0 or newer

This plugin is only for MedusaJS v2.4.0 or newer.

If you are using MedusaJS v2.3.1 or older, please use the older version of this plugin.

Configuration

Add the plugin to your file:

1import { loadEnv, defineConfig } from '@medusajs/framework/utils'
2import { UNSEND_PROVIDER_PATH } from '@rokmohar/medusa-plugin-unsend'
3
4loadEnv(process.env.NODE_ENV || 'development', process.cwd())
5
6module.exports = defineConfig({
7 // ... other config
8 plugins: [
9 // ... other plugins
10 {
11 resolve: '@rokmohar/medusa-plugin-unsend',
12 options: {
13 // Required options
14 url: process.env.UNSEND_URL ?? '',
15 api_key: process.env.UNSEND_API_KEY ?? '',
16 from: process.env.UNSEND_FROM ?? '',
17
18 // Optional configuration
19 templateDir: 'custom/templates/path', // Custom template directory
20 retry: {
21 maxAttempts: 5, // Number of retry attempts for failed sends
22 delay: 2000, // Delay between retries in milliseconds
23 },
24 rateLimit: {
25 maxPerMinute: 30, // Maximum emails per minute
26 },
27 // Environment configurations based on NODE_ENV
28 environment: {
29 development: {
30 // Development-specific overrides
31 from: 'dev@example.com',
32 rateLimit: {
33 maxPerMinute: 25,
34 },
35 },
36 staging: {
37 // Staging-specific overrides
38 from: 'stage@example.com',
39 rateLimit: {
40 maxPerMinute: 50,
41 },
42 },
43 production: {
44 // Production-specific overrides
45 from: 'prod@example.com',
46 rateLimit: {
47 maxPerMinute: 100,
48 },
49 },
50 },
51 },
52 },
53 ],
54 modules: [
55 // ... other modules
56 {
57 resolve: '@medusajs/medusa/notification',
58 dependencies: ['unsend'],
59 options: {
60 providers: [
61 // ... other providers
62 {
63 resolve: UNSEND_PROVIDER_PATH,
64 id: 'unsend',
65 options: {
66 channels: ['email'],
67 },
68 },
69 ],
70 },
71 },
72 ],
73})

ENV variables

Add the environment variables to your and file:

1# ... others vars
2UNSEND_URL=
3UNSEND_API_KEY=
4UNSEND_FROM=

If you want to use with the from this README, use the following values:

1# ... others vars
2UNSEND_URL=http://localhost:3000
3UNSEND_API_KEY=test_123456789
4UNSEND_FROM=no-reply@example.org

Email Templates

The plugin automatically loads email templates from the directory in your project root (or a custom directory specified in the configuration). Each template consists of two files:

  1. A TSX file containing the React component
  2. An optional JSON file for template metadata

Template Structure

1// src/templates/emails/ProductUpsert.tsx
2import React from 'react'
3
4const ProductUpsertEmail = (props: any) => {
5 return (
6 <div>
7 <h1>Product Updated</h1>
8 <p>Product ID: {props.productId}</p>
9 </div>
10 )
11}
12
13// Set email subject
14ProductUpsertEmail.Subject = 'Products upserted'
15
16export default ProductUpsertEmail

The email subject is determined in the following order of precedence:

  1. provided in the call
  2. field in the template's metadata JSON file
  3. static property in the TSX file
  4. Kebab-case template name (derived from the filename)

For example, if you have a template named , the subject will fall back to if no other subject is specified.

1// src/templates/emails/ProductUpsert.json
2{
3 "version": "1.0.0",
4 "subject": "Product upsert",
5 "description": "Email template for product updates",
6 "tags": ["product", "update"],
7 "category": "product-notifications"
8}

The template name will be derived from the filename (without the .tsx extension). For example, will be available as the template named .

Template Metadata

The JSON file is optional and can contain the following fields:

  • : Template version (defaults to "1.0.0")
  • : Template subject
  • : Template description
  • : Array of tags for categorizing templates
  • : Template category

Email Subject Precedence

The email subject is determined in the following order of precedence:

  1. provided in the call
  2. field in the template's metadata JSON file
  3. static property in the TSX file
  4. Kebab-case template name (derived from the filename)

For example, if you have a template named , the subject will fall back to if no other subject is specified.

Features

  • Environment-specific Configuration: Override settings for different environments (development, staging, production)
  • Rate Limiting: Prevent overwhelming the email service with configurable limits
  • Retry Mechanism: Automatic retries for failed email sends with exponential backoff
  • Template Versioning: Track template versions and changes
  • Template Metadata: Add descriptions, tags, and categories to templates
  • Custom Template Directory: Configure the location of your email templates

Subscribers

You must add the following subscribers to the :

product-upsert.ts

1import { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'
2import { IProductModuleService } from '@medusajs/framework/types'
3import { Modules } from '@medusajs/framework/utils'
4import { ProductEvents, SearchUtils } from '@medusajs/utils'
5import { UnsendService } from '@rokmohar/medusa-plugin-unsend/core'
6
7export default async function productCreatedHandler({ event: { data }, container }: SubscriberArgs<{ id: string }>) {
8 const productId = data.id
9
10 // Make sure template is registered, before creating email notifications
11 const unsendService: UnsendService = container.resolve('unsend')
12
13 const notificationModuleService = container.resolve(Modules.NOTIFICATION)
14 await notificationModuleService.createNotifications({
15 to: 'first.last@example.org',
16 channel: 'email',
17 // Use name of the registered template
18 template: 'product-upsert',
19 // Set email subject
20 content: {
21 subject: 'Product upserted',
22 },
23 })
24}
25
26export const config: SubscriberConfig = {
27 event: [ProductEvents.PRODUCT_CREATED, ProductEvents.PRODUCT_UPDATED],
28}

docker-compose

You can add the following configuration for Unsend to your :

1services:
2 # ... other services
3
4 unsend:
5 image: 'unsend/unsend:latest'
6 port:
7 - '3000:3000'

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

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

Nodemailer

От Perseides

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

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

Mailgun

От Webbers

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

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

Postmark

От Bram-hammer

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

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

Еще от этого автора

Посмотреть все
Поиск
MeiliSearch logo

MeiliSearch

От Rokmohar

Open-source поисковый движок для вашей витрины

Загрузка данных
GitHubnpm
Платежи
Manual Payment logo

Manual Payment

От Rokmohar

Дефолтный провайдер для ручного приёма оплаты

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