Unified email delivery and template management system with UI components
npm install @contentgrowth/content-emailingA comprehensive email management and delivery package designed for Cloudflare Workers.
This package provides a complete solution for handling transactional emails, managing templates (with Markdown and variable substitution), and tracking email events (opens, clicks). It relies on Cloudflare D1 for storage and supports optional Durable Objects for high-performance caching.
- Multi-Provider Support: Switch between MailChannels, SendGrid, Resend, SendPulse, or Mock (for testing) via configuration.
- Template Management: Create and edit email templates using Markdown.
- Dynamic Variables: Mustache-style variable substitution ({{ user_name }}) in subjects and bodies.
- Email Tracking: Built-in support for tracking email opens (pixel) and link clicks.
- Cloudflare D1: Stores templates, settings, and logs in D1 SQL database.
- Durable Objects Cache: Optional caching layer for high-speed template retrieval.
- React Components: Ready-to-use UI components for managing templates (TemplateManager, TemplateEditor).
- Runtime: Cloudflare Workers (or compatible environment like Hono on Node.js with D1 bindings).
- Framework: built with Hono.
- Database: Cloudflare D1.
``bash`
npm install @emails/backend
In your worker or Hono app:
`javascript
import { EmailService } from '@emails/backend';
// Initialize with your environment (needs DB binding)
// Auto-detects 'EMAIL_TEMPLATE_CACHE' Durable Object if present!
const emailService = new EmailService(env, {
// Optional: Rename tables if needed
emailTablePrefix: 'system_email_', // default (for templates/logs)
// emailSettingsTable: 'system_settings', // default (for settings)
// emailSettingsKeyPrefix: 'email_', // Optional: filter settings in shared table
defaults: {
fromName: 'My App',
fromAddress: 'noreply@myapp.com',
provider: 'resend' // or 'mailchannels', 'sendgrid', 'mock'
},
// API keys from env
resend_api_key: env.RESEND_API_KEY
});
`
The "Magic" Way (Auto-detection):
1. Add a Durable Object binding named EMAIL_TEMPLATE_CACHE to your wrangler.toml.EmailingCacheDO
2. Point it to the class from this package.EmailService(env)
3. Initialize normally. It will automatically find and use the cache.
wrangler.toml:
`toml
[[durable_objects.bindings]]
name = "EMAIL_TEMPLATE_CACHE"
class_name = "EmailTemplateCacheDO"
[[migrations]]
tag = "v1"
new_classes = ["EmailTemplateCacheDO"]
`
The Explicit Way:
If you use a custom binding name or cache implementation:
`javascript
import { EmailService, createDOCacheProvider } from '@emails/backend';
const cache = createDOCacheProvider(env.MY_CUSTOM_BINDING);
const service = new EmailService(env, config, cache);
`
Custom Cache Provider Interface:
You can also implement your own cache provider (e.g., using Redis/KV). It must match this interface:
`javascript
const myCustomCache = {
// Return template object or null
async getTemplate(templateId) {
// implementation
},
// Called when template is saved/updated
async putTemplate(template) {
// implementation (usually just invalidates cache)
},
// Called when template is deleted
async deleteTemplate(templateId) {
// implementation
}
};
const service = new EmailService(env, config, myCustomCache);
``
const service = new EmailService(env, config, myCustomCache);
The package supports a robust caching strategy for email settings (provider API keys, SMTP config, etc.).
Case A: Default System Settings (Zero Config)
If you store settings in the system_settings table (default schema), the Durable Object handles everything automatically:EmailService
1. asks DO for settings.
2. If not cached, DO queries D1 directly (Read-Through).
3. If cached, returns instantly.
Case B: Component/Tenant Settings (Custom Logic)
If you need to load settings from a custom source (e.g., tenant tables, KV, external API), simple provide loader/updater callbacks:
`javascript
const emailService = new EmailService(env, {
// Custom Loader (Read-Aside)
// The service will load this, THEN cache it in the DO for you.
settingsLoader: async (profile, tenantId) => {
return await env.TENANT_DB.prepare('SELECT * FROM tenant_config WHERE id = ?').bind(tenantId).first();
},
// Custom Updater (Write-Aside)
// required if you use saveSettings()
settingsUpdater: async (profile, tenantId, settings) => {
await env.TENANT_DB.prepare('UPDATE tenant_config SET ...').run();
}
});
`
Ensure your D1 database has the required tables. See examples/mocks/MockD1.js for the schema structure, or refer to the provided SQL migration files (if available).
Tables needed:
- system_email_templatessystem_settings
- system_email_sends
- (for logs)
Mount the management routes in your Hono app:
`javascript
import { createTemplateRoutes, createTrackingRoutes } from '@emails/backend';
// Template management (protected routes recommended)
app.route('/api/templates', createTemplateRoutes(emailService));
// Public tracking routes (opens/clicks)
app.route('/email', createTrackingRoutes(emailService));
`
A fully functional example server is included in examples/. It uses a Mock D1 implementation so you can run it locally without deploying to Cloudflare.
`bash`
cd examples
npm install
npm start
Visit http://localhost:3456/portal/ to try the Template Manager UI.
Configure your provider using standard environment variables or pass them in the config object:
- EMAIL_PROVIDER: resend, sendgrid, mailchannels, sendpulse, or mockRESEND_API_KEY
- SENDGRID_API_KEY
- SENDPULSE_CLIENT_ID
- / SENDPULSE_CLIENT_SECRET
This package is "Cloudflare-native". It expects env.DB to be a D1 binding. If running outside Cloudflare (e.g. Node.js), you must provide a D1-compatible mock or adapter, as demonstrated in the examples/` folder.