@contentgrowth/content-emailing
v0.7.2
Published
Unified email delivery and template management system with UI components
Readme
@emails/backend
A 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.
Features
- 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).
Requirements
- Runtime: Cloudflare Workers (or compatible environment like Hono on Node.js with D1 bindings).
- Framework: built with Hono.
- Database: Cloudflare D1.
Installation
npm install @emails/backendSetup & Usage
1. Initialize Email Service
In your worker or Hono app:
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: '[email protected]',
provider: 'resend' // or 'mailchannels', 'sendgrid', 'mock'
},
// API keys from env
resend_api_key: env.RESEND_API_KEY
});2.- EmailingCacheDO.js - Durable Object for caching templates & settings, you can enable the read-through cache using Cloudflare Durable Objects.
The "Magic" Way (Auto-detection):
- Add a Durable Object binding named
EMAIL_TEMPLATE_CACHEto yourwrangler.toml. - Point it to the
EmailingCacheDOclass from this package. - Initialize
EmailService(env)normally. It will automatically find and use the cache.
wrangler.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:
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:
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);
### 3. Settings Management (Hybrid Caching)
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:
1. `EmailService` 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();
}
});4. Database Schema
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_settingssystem_email_sends(for logs)
5. Add API Routes
Mount the management routes in your Hono app:
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));Running the Example
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.
cd examples
npm install
npm startVisit http://localhost:3456/portal/ to try the Template Manager UI.
Environment Variables
Configure your provider using standard environment variables or pass them in the config object:
EMAIL_PROVIDER:resend,sendgrid,mailchannels,sendpulse, ormockRESEND_API_KEYSENDGRID_API_KEYSENDPULSE_CLIENT_ID/SENDPULSE_CLIENT_SECRET
Architecture Note
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.
