Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat: Add email-gateway skill + research fallbacks for agents

Jezf923c7afef6a
diff --git a/.claude/agents/doc-validator.md b/.claude/agents/doc-validator.md
index bf960a5c..0f0fec22 100644
--- a/.claude/agents/doc-validator.md
+++ b/.claude/agents/doc-validator.md
@@ -69,6 +69,19 @@ grep -rn "TODO\|FIXME\|XXX" skills/[skill]/
npm view [package] version
```
+## Research Fallbacks
+
+When verifying external links or fetching documentation for comparison:
+
+1. **WebFetch** - Try first (fastest)
+2. **Firecrawl** - Use `firecrawl-scraper` skill if WebFetch returns blocks or incomplete content
+3. **Browser Rendering** - Use `cloudflare-browser-rendering` skill for JavaScript-heavy pages
+
+**Decision tree:**
+- Simple doc page? → WebFetch
+- Returns block/incomplete? → Firecrawl with stealth mode
+- Needs JS interaction? → Browser Rendering
+
## Severity Levels
| Level | Meaning | Action |
diff --git a/.claude/agents/skill-auditor.md b/.claude/agents/skill-auditor.md
index 4e4bbea0..ee917db5 100644
--- a/.claude/agents/skill-auditor.md
+++ b/.claude/agents/skill-auditor.md
@@ -36,9 +36,29 @@ If the prompt says "deep", "thorough", or "comprehensive", do a deep audit with
6. **Apply fixes** - Update skill with missing information
7. **Report** - Full audit report with gaps and fixes
+## Research Fallbacks
+
+When WebFetch returns incomplete content, blocks, or JavaScript-rendered pages:
+
+1. **Firecrawl** (stealth mode, anti-bot bypass):
+ - Use `firecrawl-scraper` skill for sites that block scrapers
+ - Handles JavaScript rendering and CAPTCHA bypass
+ - Best for: Documentation behind bot protection, SPAs
+
+2. **Cloudflare Browser Rendering** (Puppeteer/Playwright):
+ - Use `cloudflare-browser-rendering` skill for full browser automation
+ - Can screenshot, execute JS, navigate complex flows
+ - Best for: Interactive docs, authenticated content
+
+**Decision tree:**
+- WebFetch works? → Use it (fastest)
+- Page needs JS? → Try Firecrawl first
+- Site blocks scrapers? → Firecrawl with stealth mode
+- Need to interact (click, scroll)? → Browser Rendering
+
## Official Documentation Sources
-**ALWAYS use WebFetch to verify against official docs for deep audits:**
+**Start with WebFetch, escalate to Firecrawl/Browser Rendering if needed:**
| Technology | Documentation URL |
|------------|-------------------|
diff --git a/.claude/agents/skill-creator.md b/.claude/agents/skill-creator.md
index 684cd93d..57fc3dbc 100644
--- a/.claude/agents/skill-creator.md
+++ b/.claude/agents/skill-creator.md
@@ -34,6 +34,26 @@ Before writing content:
- Identify common errors (GitHub issues, Stack Overflow)
- Note breaking changes from recent releases
+**Research Fallbacks (when WebFetch isn't enough):**
+
+If WebFetch returns incomplete content, blocks, or JavaScript-rendered pages:
+
+1. **Firecrawl** (stealth mode, anti-bot bypass):
+ - Use `firecrawl-scraper` skill for sites that block scrapers
+ - Handles JavaScript rendering and CAPTCHA bypass
+ - Best for: Documentation behind bot protection, SPAs
+
+2. **Cloudflare Browser Rendering** (Puppeteer/Playwright):
+ - Use `cloudflare-browser-rendering` skill for full browser automation
+ - Can screenshot, execute JS, navigate complex flows
+ - Best for: Interactive docs, authenticated content
+
+**Decision tree:**
+- WebFetch works? → Use it (fastest)
+- Page needs JS? → Try Firecrawl first
+- Site blocks scrapers? → Firecrawl with stealth mode
+- Need to interact (click, scroll)? → Browser Rendering
+
### 3. SKILL.md Structure
Required sections:
diff --git a/skills/email-gateway/README.md b/skills/email-gateway/README.md
new file mode 100644
index 00000000..f7fa986b
--- /dev/null
+++ b/skills/email-gateway/README.md
@@ -0,0 +1,108 @@
+# Email Gateway (Multi-Provider)
+
+Multi-provider email sending skill for Cloudflare Workers and Node.js applications. Comprehensive coverage of Resend, SendGrid, Mailgun, and SMTP2Go APIs.
+
+## Auto-Trigger Keywords
+
+This skill should be suggested when the user mentions:
+
+**Technology Names:**
+- resend, resend api, resend.com
+- sendgrid, sendgrid api, twilio sendgrid
+- mailgun, mailgun api
+- smtp2go, smtp2go api
+- email api, email service, email provider
+- transactional email, transactional emails
+
+**Use Cases:**
+- send email, sending emails, email delivery
+- password reset email, verification email, confirmation email
+- bulk email, batch email, mass email
+- email templates, dynamic templates, react email
+- email webhooks, bounce handling, complaint handling
+- email attachments, file attachments
+- smtp relay, email relay
+
+**Error Messages:**
+- "unauthorized" (resend, sendgrid, mailgun, smtp2go)
+- "validation error" (resend, smtp2go)
+- "rate limit exceeded" (resend, sendgrid, mailgun, smtp2go)
+- "domain not verified" (resend, sendgrid, mailgun, smtp2go)
+- "invalid email format" (all providers)
+- "payload too large" (sendgrid)
+- "attachment size exceeds" (resend, sendgrid, mailgun)
+- "invalid template id" (sendgrid, mailgun)
+- "failed to deliver" (all providers)
+
+**React Email:**
+- react email, react-email, @react-email/components
+- jsx email, component email, email components
+- html email templates, responsive email
+
+**Webhooks:**
+- email bounced, email delivered, email opened, email clicked
+- bounce webhook, delivery webhook, open tracking, click tracking
+- spam complaint, unsubscribe webhook
+- webhook signature, verify webhook, webhook verification
+
+**Migration:**
+- switch from sendgrid to resend
+- migrate from mailgun to sendgrid
+- change email provider, email provider abstraction
+
+## What This Skill Covers
+
+1. **Provider Setup** - Configuration for Resend, SendGrid, Mailgun, SMTP2Go
+2. **Sending Patterns** - Transactional, batch, templates, attachments
+3. **React Email** - Component-driven email design (Resend)
+4. **Dynamic Templates** - Handlebars/variable substitution
+5. **Webhooks** - Event tracking, signature verification, bounce handling
+6. **Error Handling** - Provider-specific error codes and recovery
+7. **Rate Limiting** - Exponential backoff, quota tracking
+8. **Migration** - Provider abstraction layer for switching
+9. **Testing** - Connectivity tests, test mode sending
+
+## Quick Example
+
+```typescript
+// Resend - Modern, React Email support
+const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ subject: 'Welcome!',
+ html: '<h1>Hello World</h1>',
+ }),
+});
+
+// SendGrid - Enterprise scale
+const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: [{ email: '[email protected]' }],
+ }],
+ from: { email: '[email protected]' },
+ subject: 'Welcome!',
+ content: [{
+ type: 'text/html',
+ value: '<h1>Hello World</h1>',
+ }],
+ }),
+});
+```
+
+## Related Skills
+
+- **cloudflare-worker-base** - Cloudflare Workers setup
+- **react-hook-form-zod** - Form validation before sending
+- **project-planning** - Planning email features in applications
diff --git a/skills/email-gateway/SKILL.md b/skills/email-gateway/SKILL.md
new file mode 100644
index 00000000..64e71450
--- /dev/null
+++ b/skills/email-gateway/SKILL.md
@@ -0,0 +1,1403 @@
+---
+name: email-gateway
+description: |
+ Multi-provider email sending for Cloudflare Workers and Node.js applications.
+
+ Build transactional email systems with Resend (React Email support), SendGrid (enterprise scale),
+ Mailgun (developer webhooks), or SMTP2Go (reliable relay). Includes template patterns, webhook
+ verification, attachment handling, and error recovery. Use when sending emails via API, handling
+ bounces/complaints, or migrating between providers.
+
+metadata:
+ keywords:
+ - resend
+ - sendgrid
+ - mailgun
+ - smtp2go
+ - email api
+ - transactional email
+ - react email
+ - email webhooks
+ - bounce handling
+ - email templates
+ - smtp relay
+license: MIT
+---
+
+# Email Gateway (Multi-Provider)
+
+**Status**: Production Ready ✅
+**Last Updated**: 2026-01-10
+**Providers**: Resend, SendGrid, Mailgun, SMTP2Go
+
+---
+
+## Quick Start
+
+Choose your provider based on needs:
+
+| Provider | Best For | Key Feature | Free Tier |
+|----------|----------|-------------|-----------|
+| **Resend** | Modern apps, React Email | JSX templates | 100/day, 3k/month |
+| **SendGrid** | Enterprise scale | Dynamic templates | 100/day forever |
+| **Mailgun** | Developer webhooks | Event tracking | 100/day |
+| **SMTP2Go** | Reliable relay, AU | Simple API | 1k/month trial |
+
+### Resend (Recommended for New Projects)
+
+```typescript
+const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ subject: 'Welcome!',
+ html: '<h1>Hello World</h1>',
+ }),
+});
+
+const data = await response.json();
+// { id: "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794" }
+```
+
+### SendGrid (Enterprise)
+
+```typescript
+const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: [{ email: '[email protected]' }],
+ }],
+ from: { email: '[email protected]' },
+ subject: 'Welcome!',
+ content: [{
+ type: 'text/html',
+ value: '<h1>Hello World</h1>',
+ }],
+ }),
+});
+
+// Returns 202 on success (no body)
+```
+
+### Mailgun
+
+```typescript
+const formData = new FormData();
+formData.append('from', '[email protected]');
+formData.append('to', '[email protected]');
+formData.append('subject', 'Welcome!');
+formData.append('html', '<h1>Hello World</h1>');
+
+const response = await fetch(
+ `https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ }
+);
+
+const data = await response.json();
+// { id: "<[email protected]>", message: "Queued. Thank you." }
+```
+
+### SMTP2Go
+
+```typescript
+const response = await fetch('https://api.smtp2go.com/v3/email/send', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ api_key: env.SMTP2GO_API_KEY,
+ to: ['<[email protected]>'],
+ sender: '[email protected]',
+ subject: 'Welcome!',
+ html_body: '<h1>Hello World</h1>',
+ }),
+});
+
+const data = await response.json();
+// { data: { succeeded: 1, failed: 0, email_id: "..." } }
+```
+
+---
+
+## Provider Comparison
+
+### Features
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| **React Email** | ✅ Native | ❌ | ❌ | ❌ |
+| **Dynamic Templates** | ✅ | ✅ | ✅ | ✅ |
+| **Batch Sending** | 50/request | 1000/request | 1000/request | 100/request |
+| **Webhooks** | ✅ | ✅ | ✅ | ✅ |
+| **SMTP** | ✅ | ✅ | ✅ | ✅ Primary |
+| **IP Warmup** | Managed | Manual | Manual | Managed |
+| **Dedicated IPs** | Enterprise | $90+/mo | $80+/mo | Custom |
+| **Analytics** | Basic | Advanced | Advanced | Good |
+| **A/B Testing** | ❌ | ✅ | ✅ | ❌ |
+
+### Rate Limits (Free Tier)
+
+| Provider | Daily | Monthly | Overage Cost |
+|----------|-------|---------|--------------|
+| **Resend** | 100 | 3,000 | $1/1k |
+| **SendGrid** | 100 | Forever | $15 for 10k |
+| **Mailgun** | 100 | Forever | $15 for 10k |
+| **SMTP2Go** | ~33 | 1,000 trial | $10 for 10k |
+
+### API Limits
+
+| Provider | Requests/sec | Burst | Retry After Header |
+|----------|--------------|-------|-------------------|
+| **Resend** | 10 | Yes | ✅ |
+| **SendGrid** | 600 | Yes | ✅ |
+| **Mailgun** | Varies | Yes | ✅ |
+| **SMTP2Go** | 10 | Limited | ✅ |
+
+### Message Limits
+
+| Provider | Max Size | Attachments | Max Recipients |
+|----------|----------|-------------|----------------|
+| **Resend** | 40 MB | 40 MB total | 50/request |
+| **SendGrid** | 20 MB | 20 MB total | 1000/request |
+| **Mailgun** | 25 MB | 25 MB total | 1000/request |
+| **SMTP2Go** | 50 MB | 50 MB total | 100/request |
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+# Resend
+RESEND_API_KEY=re_xxxxxxxxx
+
+# SendGrid
+SENDGRID_API_KEY=SG.xxxxxxxxx
+
+# Mailgun
+MAILGUN_API_KEY=xxxxxxxx-xxxxxxxx-xxxxxxxx
+MAILGUN_DOMAIN=mg.yourdomain.com
+MAILGUN_REGION=us # or eu
+
+# SMTP2Go
+SMTP2GO_API_KEY=api-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+```
+
+### Wrangler Secrets (Cloudflare Workers)
+
+```bash
+# Set secrets
+echo "re_xxxxxxxxx" | npx wrangler secret put RESEND_API_KEY
+echo "SG.xxxxxxxxx" | npx wrangler secret put SENDGRID_API_KEY
+echo "xxxxxxxx-xxxxxxxx-xxxxxxxx" | npx wrangler secret put MAILGUN_API_KEY
+echo "api-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" | npx wrangler secret put SMTP2GO_API_KEY
+
+# Deploy to activate
+npx wrangler deploy
+```
+
+### TypeScript Types
+
+```typescript
+// Resend
+interface ResendEmail {
+ from: string;
+ to: string | string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ cc?: string | string[];
+ bcc?: string | string[];
+ replyTo?: string | string[];
+ headers?: Record<string, string>;
+ attachments?: Array<{
+ filename: string;
+ content: string; // base64
+ }>;
+ tags?: Record<string, string>;
+ scheduledAt?: string; // ISO 8601
+}
+
+interface ResendResponse {
+ id: string;
+}
+
+// SendGrid
+interface SendGridEmail {
+ personalizations: Array<{
+ to: Array<{ email: string; name?: string }>;
+ cc?: Array<{ email: string; name?: string }>;
+ bcc?: Array<{ email: string; name?: string }>;
+ subject?: string;
+ dynamic_template_data?: Record<string, unknown>;
+ }>;
+ from: { email: string; name?: string };
+ subject?: string;
+ content?: Array<{
+ type: 'text/plain' | 'text/html';
+ value: string;
+ }>;
+ template_id?: string;
+ attachments?: Array<{
+ content: string; // base64
+ filename: string;
+ type?: string;
+ disposition?: 'inline' | 'attachment';
+ }>;
+}
+
+// Mailgun
+interface MailgunEmail {
+ from: string;
+ to: string | string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ cc?: string | string[];
+ bcc?: string | string[];
+ 'h:Reply-To'?: string;
+ template?: string;
+ 'h:X-Mailgun-Variables'?: string; // JSON
+ attachment?: File | File[];
+ inline?: File | File[];
+ 'o:tag'?: string | string[];
+ 'o:tracking'?: 'yes' | 'no';
+ 'o:tracking-clicks'?: 'yes' | 'no' | 'htmlonly';
+ 'o:tracking-opens'?: 'yes' | 'no';
+}
+
+interface MailgunResponse {
+ id: string;
+ message: string;
+}
+
+// SMTP2Go
+interface SMTP2GoEmail {
+ api_key: string;
+ to: string[];
+ sender: string;
+ subject: string;
+ html_body?: string;
+ text_body?: string;
+ custom_headers?: Array<{
+ header: string;
+ value: string;
+ }>;
+ attachments?: Array<{
+ filename: string;
+ fileblob: string; // base64
+ mimetype?: string;
+ }>;
+}
+
+interface SMTP2GoResponse {
+ data: {
+ succeeded: number;
+ failed: number;
+ failures?: string[];
+ email_id?: string;
+ };
+}
+```
+
+---
+
+## Common Patterns
+
+### 1. Transactional Emails
+
+**Password Reset**:
+
+```typescript
+// templates/password-reset.ts
+export async function sendPasswordReset(
+ provider: 'resend' | 'sendgrid' | 'mailgun' | 'smtp2go',
+ to: string,
+ resetToken: string,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;
+
+ const html = `
+ <h1>Reset Your Password</h1>
+ <p>Click the link below to reset your password:</p>
+ <a href="${resetUrl}">Reset Password</a>
+ <p>This link expires in 1 hour.</p>
+ `;
+
+ switch (provider) {
+ case 'resend':
+ return sendViaResend(to, 'Reset Your Password', html, env);
+ case 'sendgrid':
+ return sendViaSendGrid(to, 'Reset Your Password', html, env);
+ case 'mailgun':
+ return sendViaMailgun(to, 'Reset Your Password', html, env);
+ case 'smtp2go':
+ return sendViaSMTP2Go(to, 'Reset Your Password', html, env);
+ }
+}
+
+async function sendViaResend(
+ to: string,
+ subject: string,
+ html: string,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ to,
+ subject,
+ html,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ return { success: false, error };
+ }
+
+ const data = await response.json();
+ return { success: true, id: data.id };
+}
+```
+
+### 2. Batch Sending
+
+**Resend (max 50 recipients)**:
+
+```typescript
+async function sendBatchResend(
+ recipients: string[],
+ subject: string,
+ html: string,
+ env: Env
+): Promise<Array<{ email: string; id?: string; error?: string }>> {
+ const results: Array<{ email: string; id?: string; error?: string }> = [];
+
+ // Chunk into groups of 50
+ for (let i = 0; i < recipients.length; i += 50) {
+ const chunk = recipients.slice(i, i + 50);
+
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ to: chunk,
+ subject,
+ html,
+ }),
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ chunk.forEach(email => results.push({ email, id: data.id }));
+ } else {
+ const error = await response.text();
+ chunk.forEach(email => results.push({ email, error }));
+ }
+ }
+
+ return results;
+}
+```
+
+**SendGrid (max 1000 personalizations)**:
+
+```typescript
+async function sendBatchSendGrid(
+ recipients: Array<{ email: string; name?: string; data?: Record<string, unknown> }>,
+ templateId: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: recipients.map(r => ({
+ to: [{ email: r.email, name: r.name }],
+ dynamic_template_data: r.data || {},
+ })),
+ from: { email: '[email protected]' },
+ template_id: templateId,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ return { success: false, error };
+ }
+
+ return { success: true };
+}
+```
+
+### 3. React Email Templates (Resend Only)
+
+**Install React Email**:
+
+```bash
+npm install react-email @react-email/components
+```
+
+**Create Template**:
+
+```tsx
+// emails/welcome.tsx
+import {
+ Html,
+ Head,
+ Body,
+ Container,
+ Heading,
+ Text,
+ Button,
+} from '@react-email/components';
+
+interface WelcomeEmailProps {
+ name: string;
+ confirmUrl: string;
+}
+
+export default function WelcomeEmail({ name, confirmUrl }: WelcomeEmailProps) {
+ return (
+ <Html>
+ <Head />
+ <Body style={{ fontFamily: 'Arial, sans-serif' }}>
+ <Container>
+ <Heading>Welcome, {name}!</Heading>
+ <Text>Thanks for signing up. Please confirm your email address:</Text>
+ <Button href={confirmUrl} style={{ background: '#000', color: '#fff' }}>
+ Confirm Email
+ </Button>
+ </Container>
+ </Body>
+ </Html>
+ );
+}
+```
+
+**Send via Resend SDK (Node.js)**:
+
+```typescript
+import { Resend } from 'resend';
+import WelcomeEmail from './emails/welcome';
+
+const resend = new Resend(process.env.RESEND_API_KEY);
+
+await resend.emails.send({
+ subject: 'Welcome!',
+ react: WelcomeEmail({ name: 'Alice', confirmUrl: 'https://...' }),
+});
+```
+
+**Send via Workers (render to HTML first)**:
+
+```typescript
+import { render } from '@react-email/render';
+import WelcomeEmail from './emails/welcome';
+
+const html = render(WelcomeEmail({ name: 'Alice', confirmUrl: 'https://...' }));
+
+await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ subject: 'Welcome!',
+ html,
+ }),
+});
+```
+
+### 4. Dynamic Templates
+
+**SendGrid**:
+
+```typescript
+// 1. Create template in SendGrid dashboard with handlebars
+// Subject: Welcome {{name}}!
+// Body: <h1>Hi {{name}}</h1><p>Your code: {{confirmationCode}}</p>
+
+// 2. Send with template ID
+const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: [{ email: '[email protected]' }],
+ dynamic_template_data: {
+ name: 'Alice',
+ confirmationCode: 'ABC123',
+ },
+ }],
+ from: { email: '[email protected]' },
+ template_id: 'd-xxxxxxxxxxxxxxxxxxxxxxxx',
+ }),
+});
+```
+
+**Mailgun**:
+
+```typescript
+// 1. Create template in Mailgun dashboard or via API
+// Use {{name}} and {{confirmationCode}} variables
+
+// 2. Send with template name
+const formData = new FormData();
+formData.append('from', '[email protected]');
+formData.append('to', '[email protected]');
+formData.append('subject', 'Welcome');
+formData.append('template', 'welcome-template');
+formData.append('h:X-Mailgun-Variables', JSON.stringify({
+ name: 'Alice',
+ confirmationCode: 'ABC123',
+}));
+
+const response = await fetch(
+ `https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ }
+);
+```
+
+### 5. Attachments
+
+**Resend**:
+
+```typescript
+const fileBuffer = await file.arrayBuffer();
+const base64Content = btoa(String.fromCharCode(...new Uint8Array(fileBuffer)));
+
+await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ subject: 'Your Invoice',
+ html: '<p>Attached is your invoice.</p>',
+ attachments: [{
+ filename: 'invoice.pdf',
+ content: base64Content,
+ }],
+ }),
+});
+```
+
+**SendGrid**:
+
+```typescript
+const fileBuffer = await file.arrayBuffer();
+const base64Content = btoa(String.fromCharCode(...new Uint8Array(fileBuffer)));
+
+const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: [{ email: '[email protected]' }],
+ }],
+ from: { email: '[email protected]' },
+ subject: 'Your Invoice',
+ content: [{ type: 'text/html', value: '<p>Attached is your invoice.</p>' }],
+ attachments: [{
+ content: base64Content,
+ filename: 'invoice.pdf',
+ type: 'application/pdf',
+ disposition: 'attachment',
+ }],
+ }),
+});
+```
+
+**Mailgun** (uses FormData with File):
+
+```typescript
+const formData = new FormData();
+formData.append('from', '[email protected]');
+formData.append('to', '[email protected]');
+formData.append('subject', 'Your Invoice');
+formData.append('html', '<p>Attached is your invoice.</p>');
+formData.append('attachment', file); // File object directly
+
+const response = await fetch(
+ `https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ }
+);
+```
+
+### 6. Webhooks (Event Tracking)
+
+**Resend Webhooks**:
+
+Events: `email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained`, `email.opened`, `email.clicked`
+
+```typescript
+// Verify webhook signature
+import { createHmac } from 'crypto';
+
+export async function verifyResendWebhook(
+ request: Request,
+ secret: string
+): Promise<boolean> {
+ const signature = request.headers.get('svix-signature');
+ const timestamp = request.headers.get('svix-timestamp');
+ const body = await request.text();
+
+ if (!signature || !timestamp) return false;
+
+ const signedContent = `${timestamp}.${body}`;
+ const expectedSignature = createHmac('sha256', secret)
+ .update(signedContent)
+ .digest('base64');
+
+ return signature.includes(expectedSignature);
+}
+
+// Handle webhook
+export async function handleResendWebhook(request: Request, env: Env) {
+ const isValid = await verifyResendWebhook(request, env.RESEND_WEBHOOK_SECRET);
+ if (!isValid) {
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ const event = await request.json();
+
+ switch (event.type) {
+ case 'email.bounced':
+ // Mark email as invalid
+ await markEmailInvalid(event.data.email);
+ break;
+ case 'email.complained':
+ // Unsubscribe user
+ await unsubscribeUser(event.data.email);
+ break;
+ }
+
+ return new Response('OK');
+}
+```
+
+**SendGrid Webhooks**:
+
+```typescript
+// Verify webhook signature (requires express-style body parser)
+import { EventWebhook, EventWebhookHeader } from '@sendgrid/eventwebhook';
+
+export async function verifySendGridWebhook(
+ request: Request,
+ publicKey: string
+): Promise<boolean> {
+ const signature = request.headers.get(EventWebhookHeader.SIGNATURE());
+ const timestamp = request.headers.get(EventWebhookHeader.TIMESTAMP());
+ const body = await request.text();
+
+ const eventWebhook = new EventWebhook();
+ const ecPublicKey = eventWebhook.convertPublicKeyToECDSA(publicKey);
+
+ return eventWebhook.verifySignature(
+ ecPublicKey,
+ body,
+ signature!,
+ timestamp!
+ );
+}
+
+// Handle webhook
+export async function handleSendGridWebhook(request: Request, env: Env) {
+ const events = await request.json();
+
+ for (const event of events) {
+ switch (event.event) {
+ case 'bounce':
+ await markEmailInvalid(event.email);
+ break;
+ case 'spamreport':
+ await unsubscribeUser(event.email);
+ break;
+ }
+ }
+
+ return new Response('OK');
+}
+```
+
+**Mailgun Webhooks**:
+
+```typescript
+// Verify webhook signature
+import { createHmac } from 'crypto';
+
+export function verifyMailgunWebhook(
+ timestamp: string,
+ token: string,
+ signature: string,
+ signingKey: string
+): boolean {
+ const encoded = createHmac('sha256', signingKey)
+ .update(`${timestamp}${token}`)
+ .digest('hex');
+
+ return encoded === signature;
+}
+
+// Handle webhook
+export async function handleMailgunWebhook(request: Request, env: Env) {
+ const data = await request.json();
+
+ const isValid = verifyMailgunWebhook(
+ data.signature.timestamp,
+ data.signature.token,
+ data.signature.signature,
+ env.MAILGUN_WEBHOOK_SIGNING_KEY
+ );
+
+ if (!isValid) {
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ switch (data['event-data'].event) {
+ case 'failed':
+ if (data['event-data'].severity === 'permanent') {
+ await markEmailInvalid(data['event-data'].recipient);
+ }
+ break;
+ case 'complained':
+ await unsubscribeUser(data['event-data'].recipient);
+ break;
+ }
+
+ return new Response('OK');
+}
+```
+
+**SMTP2Go Webhooks**:
+
+```typescript
+// Verify webhook signature
+import { createHmac } from 'crypto';
+
+export function verifySMTP2GoWebhook(
+ body: string,
+ signature: string,
+ secret: string
+): boolean {
+ const expectedSignature = createHmac('sha256', secret)
+ .update(body)
+ .digest('hex');
+
+ return expectedSignature === signature;
+}
+
+// Handle webhook
+export async function handleSMTP2GoWebhook(request: Request, env: Env) {
+ const signature = request.headers.get('X-Smtp2go-Signature');
+ const body = await request.text();
+
+ if (!signature || !verifySMTP2GoWebhook(body, signature, env.SMTP2GO_WEBHOOK_SECRET)) {
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ const event = JSON.parse(body);
+
+ switch (event.event) {
+ case 'bounce':
+ await markEmailInvalid(event.email);
+ break;
+ case 'spam':
+ await unsubscribeUser(event.email);
+ break;
+ }
+
+ return new Response('OK');
+}
+```
+
+---
+
+## Error Handling
+
+### Resend Errors
+
+| Status | Error | Cause | Fix |
+|--------|-------|-------|-----|
+| 401 | Unauthorized | Invalid API key | Check RESEND_API_KEY |
+| 422 | Validation error | Invalid email format | Validate emails before sending |
+| 429 | Rate limit exceeded | Too many requests | Implement exponential backoff |
+| 500 | Internal error | Resend service issue | Retry with backoff |
+
+**Common validation errors**:
+- `to` field required
+- Invalid email format
+- `from` domain not verified
+- Attachment size exceeds 40 MB
+
+**Error response format**:
+
+```json
+{
+ "statusCode": 422,
+ "message": "Validation error",
+ "name": "validation_error"
+}
+```
+
+### SendGrid Errors
+
+| Status | Error | Cause | Fix |
+|--------|-------|-------|-----|
+| 400 | Bad request | Malformed JSON | Check request structure |
+| 401 | Unauthorized | Invalid API key | Check SENDGRID_API_KEY |
+| 413 | Payload too large | Message > 20 MB | Reduce attachment size |
+| 429 | Too many requests | Rate limit | Implement backoff |
+
+**Common errors**:
+- Missing `personalizations`
+- Invalid template ID
+- Unverified sender address
+- Attachment encoding issues
+
+**Error response format**:
+
+```json
+{
+ "errors": [
+ {
+ "message": "The from email does not contain a valid address.",
+ "field": "from.email",
+ "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from.email"
+ }
+ ]
+}
+```
+
+### Mailgun Errors
+
+| Status | Error | Cause | Fix |
+|--------|-------|-------|-----|
+| 400 | Bad request | Invalid parameters | Check FormData fields |
+| 401 | Unauthorized | Invalid API key | Check MAILGUN_API_KEY |
+| 402 | Payment required | Quota exceeded | Upgrade plan |
+| 404 | Not found | Invalid domain | Check MAILGUN_DOMAIN |
+
+**Common errors**:
+- Domain not verified
+- Wrong region (US vs EU)
+- Invalid template variables
+- Recipient address syntax
+
+**Error response format**:
+
+```json
+{
+ "message": "Domain not found: invalid.domain.com"
+}
+```
+
+### SMTP2Go Errors
+
+| Status | Error | Cause | Fix |
+|--------|-------|-------|-----|
+| 401 | Unauthorized | Invalid API key | Check SMTP2GO_API_KEY |
+| 422 | Validation error | Invalid email format | Validate recipients |
+| 429 | Rate limit | Too many requests | Implement backoff |
+
+**Common errors**:
+- Sender domain not verified
+- Invalid recipient format (must use angle brackets: `<[email protected]>`)
+- API key not activated
+
+**Error response format**:
+
+```json
+{
+ "data": {
+ "error": "Invalid sender email address",
+ "error_code": "E_ApiResponseCodes_INVALID_SENDER_ADDRESS"
+ }
+}
+```
+
+---
+
+## Rate Limiting & Retry
+
+### Exponential Backoff Pattern
+
+```typescript
+async function sendWithRetry(
+ sendFn: () => Promise<Response>,
+ maxRetries = 3
+): Promise<Response> {
+ let lastError: Error | null = null;
+
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ try {
+ const response = await sendFn();
+
+ if (response.ok) {
+ return response;
+ }
+
+ // Check if retryable
+ if (response.status === 429 || response.status >= 500) {
+ const retryAfter = response.headers.get('Retry-After');
+ const delay = retryAfter
+ ? parseInt(retryAfter) * 1000
+ : Math.pow(2, attempt) * 1000;
+
+ await new Promise(resolve => setTimeout(resolve, delay));
+ continue;
+ }
+
+ // Non-retryable error
+ return response;
+ } catch (error) {
+ lastError = error as Error;
+ if (attempt < maxRetries - 1) {
+ await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
+ }
+ }
+ }
+
+ throw lastError || new Error('Max retries exceeded');
+}
+
+// Usage
+const response = await sendWithRetry(() =>
+ fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(email),
+ })
+);
+```
+
+### Rate Limit Tracking
+
+```typescript
+// Use KV to track rate limits per provider
+interface RateLimitState {
+ count: number;
+ resetAt: number;
+}
+
+async function checkRateLimit(
+ provider: string,
+ kv: KVNamespace
+): Promise<{ allowed: boolean; resetAt?: number }> {
+ const key = `rate-limit:${provider}`;
+ const stateJson = await kv.get(key);
+ const state: RateLimitState = stateJson ? JSON.parse(stateJson) : null;
+
+ const now = Date.now();
+
+ if (!state || now > state.resetAt) {
+ // Reset window
+ const limits: Record<string, number> = {
+ resend: 10,
+ sendgrid: 600,
+ mailgun: 100,
+ smtp2go: 10,
+ };
+
+ const newState: RateLimitState = {
+ count: 1,
+ resetAt: now + 1000, // 1 second window
+ };
+
+ await kv.put(key, JSON.stringify(newState), { expirationTtl: 60 });
+ return { allowed: true };
+ }
+
+ const limits: Record<string, number> = {
+ resend: 10,
+ sendgrid: 600,
+ mailgun: 100,
+ smtp2go: 10,
+ };
+
+ if (state.count >= limits[provider]) {
+ return { allowed: false, resetAt: state.resetAt };
+ }
+
+ state.count++;
+ await kv.put(key, JSON.stringify(state), { expirationTtl: 60 });
+ return { allowed: true };
+}
+```
+
+---
+
+## Migration Between Providers
+
+### Provider Abstraction
+
+```typescript
+// types.ts
+export interface EmailProvider {
+ send(email: EmailMessage): Promise<EmailResult>;
+ sendBatch(emails: EmailMessage[]): Promise<EmailResult[]>;
+}
+
+export interface EmailMessage {
+ from: string;
+ to: string | string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ attachments?: Attachment[];
+ tags?: Record<string, string>;
+}
+
+export interface EmailResult {
+ success: boolean;
+ id?: string;
+ error?: string;
+}
+
+export interface Attachment {
+ filename: string;
+ content: string; // base64
+}
+
+// providers/resend.ts
+export class ResendProvider implements EmailProvider {
+ constructor(private apiKey: string) {}
+
+ async send(email: EmailMessage): Promise<EmailResult> {
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ from: email.from,
+ to: email.to,
+ subject: email.subject,
+ html: email.html,
+ text: email.text,
+ attachments: email.attachments,
+ tags: email.tags,
+ }),
+ });
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ const data = await response.json();
+ return { success: true, id: data.id };
+ }
+
+ async sendBatch(emails: EmailMessage[]): Promise<EmailResult[]> {
+ return Promise.all(emails.map(email => this.send(email)));
+ }
+}
+
+// providers/sendgrid.ts
+export class SendGridProvider implements EmailProvider {
+ constructor(private apiKey: string) {}
+
+ async send(email: EmailMessage): Promise<EmailResult> {
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: Array.isArray(email.to)
+ ? email.to.map(e => ({ email: e }))
+ : [{ email: email.to }],
+ }],
+ from: { email: email.from },
+ subject: email.subject,
+ content: email.html
+ ? [{ type: 'text/html', value: email.html }]
+ : [{ type: 'text/plain', value: email.text || '' }],
+ attachments: email.attachments?.map(a => ({
+ content: a.content,
+ filename: a.filename,
+ })),
+ }),
+ });
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ return { success: true };
+ }
+
+ async sendBatch(emails: EmailMessage[]): Promise<EmailResult[]> {
+ // SendGrid supports batch via personalizations
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${this.apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: emails.map(email => ({
+ to: Array.isArray(email.to)
+ ? email.to.map(e => ({ email: e }))
+ : [{ email: email.to }],
+ subject: email.subject,
+ })),
+ from: { email: emails[0].from },
+ content: emails[0].html
+ ? [{ type: 'text/html', value: emails[0].html }]
+ : [{ type: 'text/plain', value: emails[0].text || '' }],
+ }),
+ });
+
+ if (!response.ok) {
+ return emails.map(() => ({ success: false, error: await response.text() }));
+ }
+
+ return emails.map(() => ({ success: true }));
+ }
+}
+
+// Usage
+const provider = env.EMAIL_PROVIDER === 'resend'
+ ? new ResendProvider(env.RESEND_API_KEY)
+ : new SendGridProvider(env.SENDGRID_API_KEY);
+
+await provider.send({
+ subject: 'Welcome',
+ html: '<h1>Hello</h1>',
+});
+```
+
+---
+
+## Testing
+
+### Test Provider Connectivity
+
+```typescript
+export async function testEmailProvider(
+ provider: 'resend' | 'sendgrid' | 'mailgun' | 'smtp2go',
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const testEmail = {
+ subject: 'Test Email',
+ html: '<p>This is a test email.</p>',
+ };
+
+ try {
+ switch (provider) {
+ case 'resend': {
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(testEmail),
+ });
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ return { success: true };
+ }
+
+ case 'sendgrid': {
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{ to: [{ email: testEmail.to }] }],
+ from: { email: testEmail.from },
+ subject: testEmail.subject,
+ content: [{ type: 'text/html', value: testEmail.html }],
+ }),
+ });
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ return { success: true };
+ }
+
+ case 'mailgun': {
+ const formData = new FormData();
+ formData.append('from', testEmail.from);
+ formData.append('to', testEmail.to);
+ formData.append('subject', testEmail.subject);
+ formData.append('html', testEmail.html);
+
+ const response = await fetch(
+ `https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ }
+ );
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ return { success: true };
+ }
+
+ case 'smtp2go': {
+ const response = await fetch('https://api.smtp2go.com/v3/email/send', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ api_key: env.SMTP2GO_API_KEY,
+ to: [`<${testEmail.to}>`],
+ sender: testEmail.from,
+ subject: testEmail.subject,
+ html_body: testEmail.html,
+ }),
+ });
+
+ if (!response.ok) {
+ return { success: false, error: await response.text() };
+ }
+
+ const data = await response.json();
+ if (data.data.failed > 0) {
+ return { success: false, error: data.data.failures?.join(', ') };
+ }
+
+ return { success: true };
+ }
+ }
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+}
+```
+
+---
+
+## Quick Reference
+
+### API Endpoints
+
+| Provider | Endpoint |
+|----------|----------|
+| Resend | `https://api.resend.com/emails` |
+| SendGrid | `https://api.sendgrid.com/v3/mail/send` |
+| Mailgun US | `https://api.mailgun.net/v3/{domain}/messages` |
+| Mailgun EU | `https://api.eu.mailgun.net/v3/{domain}/messages` |
+| SMTP2Go | `https://api.smtp2go.com/v3/email/send` |
+
+### Authentication Headers
+
+| Provider | Header | Format |
+|----------|--------|--------|
+| Resend | `Authorization` | `Bearer {API_KEY}` |
+| SendGrid | `Authorization` | `Bearer {API_KEY}` |
+| Mailgun | `Authorization` | `Basic {base64(api:API_KEY)}` |
+| SMTP2Go | Body field | `api_key: {API_KEY}` |
+
+### Webhook Events
+
+| Event Type | Resend | SendGrid | Mailgun | SMTP2Go |
+|------------|--------|----------|---------|---------|
+| Delivered | `email.delivered` | `delivered` | `delivered` | `delivered` |
+| Bounced | `email.bounced` | `bounce` | `failed` | `bounce` |
+| Spam | `email.complained` | `spamreport` | `complained` | `spam` |
+| Opened | `email.opened` | `open` | `opened` | `open` |
+| Clicked | `email.clicked` | `click` | `clicked` | `click` |
+
+### Support Links
+
+- **Resend**: https://resend.com/docs
+- **SendGrid**: https://www.twilio.com/docs/sendgrid
+- **Mailgun**: https://documentation.mailgun.com
+- **SMTP2Go**: https://developers.smtp2go.com
+
+---
+
+**Production Notes**:
+- Always verify sender domains before production
+- Set up DKIM/SPF/DMARC records for deliverability
+- Use dedicated IPs for high-volume sending (>100k/month)
+- Implement webhook handlers for bounce/complaint management
+- Monitor sender reputation via provider dashboards
+- Keep unsubscribe mechanisms compliant (CAN-SPAM, GDPR)
diff --git a/skills/email-gateway/references/common-errors.md b/skills/email-gateway/references/common-errors.md
new file mode 100644
index 00000000..cb3bc703
--- /dev/null
+++ b/skills/email-gateway/references/common-errors.md
@@ -0,0 +1,698 @@
+# Common Email API Errors
+
+Comprehensive error reference for all four providers with solutions.
+
+## Resend Errors
+
+### Authentication Errors
+
+**401 Unauthorized**
+
+Error:
+```json
+{
+ "statusCode": 401,
+ "message": "Missing API key",
+ "name": "missing_api_key"
+}
+```
+
+Cause: Missing or invalid `Authorization` header
+
+Fix:
+```typescript
+headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`, // Must start with "re_"
+ 'Content-Type': 'application/json',
+}
+```
+
+---
+
+### Validation Errors
+
+**422 Validation Error - Missing `to` field**
+
+Error:
+```json
+{
+ "statusCode": 422,
+ "message": "The `to` field is required.",
+ "name": "validation_error"
+}
+```
+
+Fix: Ensure `to` field is present and non-empty
+
+```typescript
+{
+ to: '[email protected]', // Required
+ subject: 'Welcome',
+ html: '<h1>Hello</h1>',
+}
+```
+
+---
+
+**422 Validation Error - Invalid Email Format**
+
+Error:
+```json
+{
+ "statusCode": 422,
+ "message": "Invalid email format",
+ "name": "validation_error"
+}
+```
+
+Fix: Validate email format before sending
+
+```typescript
+function isValidEmail(email: string): boolean {
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
+}
+
+if (!isValidEmail(to)) {
+ throw new Error('Invalid email address');
+}
+```
+
+---
+
+**422 Validation Error - Domain Not Verified**
+
+Error:
+```json
+{
+ "statusCode": 422,
+ "message": "The `from` email address domain is not verified.",
+ "name": "validation_error"
+}
+```
+
+Fix:
+1. Go to Resend dashboard → Domains
+2. Add domain and configure DNS records
+3. Wait for verification (can take up to 48 hours)
+4. Use verified domain in `from` field
+
+---
+
+**422 Validation Error - Attachment Too Large**
+
+Error:
+```json
+{
+ "statusCode": 422,
+ "message": "Attachment size exceeds 40 MB",
+ "name": "validation_error"
+}
+```
+
+Fix: Reduce attachment size or host file externally
+
+```typescript
+const MAX_SIZE = 40 * 1024 * 1024; // 40 MB
+
+if (fileSize > MAX_SIZE) {
+ // Host file on R2/S3 and send link instead
+ const fileUrl = await uploadToR2(file);
+ html += `<a href="${fileUrl}">Download file</a>`;
+}
+```
+
+---
+
+### Rate Limiting
+
+**429 Too Many Requests**
+
+Error:
+```json
+{
+ "statusCode": 429,
+ "message": "Rate limit exceeded",
+ "name": "rate_limit_exceeded"
+}
+```
+
+Response headers:
+- `X-RateLimit-Limit`: Maximum requests per window
+- `X-RateLimit-Remaining`: Requests remaining
+- `X-RateLimit-Reset`: Unix timestamp when limit resets
+- `Retry-After`: Seconds to wait before retrying
+
+Fix: Implement exponential backoff
+
+```typescript
+async function sendWithRetry(sendFn: () => Promise<Response>, maxRetries = 3) {
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ const response = await sendFn();
+
+ if (response.status === 429) {
+ const retryAfter = response.headers.get('Retry-After');
+ const delay = retryAfter ? parseInt(retryAfter) * 1000 : Math.pow(2, attempt) * 1000;
+ await new Promise(resolve => setTimeout(resolve, delay));
+ continue;
+ }
+
+ return response;
+ }
+
+ throw new Error('Max retries exceeded');
+}
+```
+
+---
+
+### Server Errors
+
+**500 Internal Server Error**
+
+Error:
+```json
+{
+ "statusCode": 500,
+ "message": "Internal server error",
+ "name": "internal_error"
+}
+```
+
+Fix: Retry with exponential backoff (transient issue)
+
+---
+
+## SendGrid Errors
+
+### Authentication Errors
+
+**401 Unauthorized**
+
+Error:
+```json
+{
+ "errors": [{
+ "message": "The provided authorization grant is invalid, expired, or revoked",
+ "field": null,
+ "help": null
+ }]
+}
+```
+
+Cause: Invalid API key
+
+Fix: Verify API key starts with `SG.` and has correct permissions
+
+```typescript
+headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`, // Must start with "SG."
+}
+```
+
+---
+
+### Validation Errors
+
+**400 Bad Request - Missing Personalizations**
+
+Error:
+```json
+{
+ "errors": [{
+ "message": "The personalizations field is required.",
+ "field": "personalizations",
+ "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations"
+ }]
+}
+```
+
+Fix: Include personalizations array
+
+```typescript
+{
+ personalizations: [{ // Required
+ to: [{ email: '[email protected]' }],
+ }],
+ from: { email: '[email protected]' },
+ subject: 'Welcome',
+ content: [{ type: 'text/html', value: '<h1>Hello</h1>' }],
+}
+```
+
+---
+
+**400 Bad Request - Invalid From Address**
+
+Error:
+```json
+{
+ "errors": [{
+ "message": "The from email does not contain a valid address.",
+ "field": "from.email",
+ "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from.email"
+ }]
+}
+```
+
+Fix: Verify sender domain
+
+1. Go to SendGrid dashboard → Settings → Sender Authentication
+2. Authenticate domain or single sender
+3. Use verified email in `from` field
+
+---
+
+**400 Bad Request - Invalid Template ID**
+
+Error:
+```json
+{
+ "errors": [{
+ "message": "The template_id is invalid.",
+ "field": "template_id",
+ "help": null
+ }]
+}
+```
+
+Fix: Verify template exists and ID is correct
+
+```bash
+# List templates via API
+curl https://api.sendgrid.com/v3/templates \
+ -H "Authorization: Bearer $SENDGRID_API_KEY"
+```
+
+---
+
+**413 Payload Too Large**
+
+Error:
+```json
+{
+ "errors": [{
+ "message": "The message size exceeds the maximum allowed (20 MB).",
+ "field": null,
+ "help": null
+ }]
+}
+```
+
+Fix: Reduce message size or split into multiple emails
+
+---
+
+### Rate Limiting
+
+**429 Too Many Requests**
+
+Response headers:
+- `X-RateLimit-Limit`: 600 requests/second
+- `X-RateLimit-Remaining`: Requests remaining
+- `X-RateLimit-Reset`: Unix timestamp
+
+Fix: Implement rate limiting (same as Resend)
+
+---
+
+## Mailgun Errors
+
+### Authentication Errors
+
+**401 Unauthorized**
+
+Error:
+```json
+{
+ "message": "Forbidden"
+}
+```
+
+Cause: Invalid API key or wrong region
+
+Fix: Verify API key and region
+
+```typescript
+// US region
+const apiUrl = 'https://api.mailgun.net/v3';
+
+// EU region
+const apiUrl = 'https://api.eu.mailgun.net/v3';
+
+headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+}
+```
+
+---
+
+### Domain Errors
+
+**404 Not Found**
+
+Error:
+```json
+{
+ "message": "Domain not found: invalid.domain.com"
+}
+```
+
+Fix: Verify domain is added and active in Mailgun dashboard
+
+---
+
+### Validation Errors
+
+**400 Bad Request - Invalid Recipient**
+
+Error:
+```json
+{
+ "message": "'to' parameter is not a valid address. please check documentation"
+}
+```
+
+Fix: Ensure email format is correct
+
+```typescript
+// Mailgun is strict about email format
+formData.append('to', '[email protected]'); // Correct
+formData.append('to', 'User <[email protected]>'); // Also correct
+formData.append('to', 'user@'); // ❌ Invalid
+```
+
+---
+
+**400 Bad Request - Invalid Template Variables**
+
+Error:
+```json
+{
+ "message": "Template variable parsing error"
+}
+```
+
+Fix: Ensure template variables are valid JSON
+
+```typescript
+formData.append('h:X-Mailgun-Variables', JSON.stringify({
+ name: 'Alice',
+ code: '123',
+})); // Must be valid JSON string
+```
+
+---
+
+### Quota Errors
+
+**402 Payment Required**
+
+Error:
+```json
+{
+ "message": "Free accounts are limited to 100 emails per day. Please upgrade."
+}
+```
+
+Fix: Upgrade plan or wait for quota reset
+
+---
+
+## SMTP2Go Errors
+
+### Authentication Errors
+
+**401 Unauthorized**
+
+Error:
+```json
+{
+ "data": {
+ "error": "Invalid API Key",
+ "error_code": "E_ApiResponseCodes_INVALID_API_KEY"
+ }
+}
+```
+
+Fix: Verify API key is active
+
+```typescript
+{
+ api_key: env.SMTP2GO_API_KEY, // Must be valid and active
+}
+```
+
+---
+
+### Validation Errors
+
+**422 Validation Error - Invalid Sender**
+
+Error:
+```json
+{
+ "data": {
+ "error": "Invalid sender email address",
+ "error_code": "E_ApiResponseCodes_INVALID_SENDER_ADDRESS"
+ }
+}
+```
+
+Fix: Verify sender domain or use verified sender
+
+---
+
+**422 Validation Error - Invalid Recipient Format**
+
+Error:
+```json
+{
+ "data": {
+ "error": "Invalid recipient format",
+ "error_code": "E_ApiResponseCodes_INVALID_RECIPIENT"
+ }
+}
+```
+
+Fix: SMTP2Go requires angle brackets for recipients
+
+```typescript
+// ❌ Wrong
+
+// ✅ Correct
+
+// Helper function
+function formatEmail(email: string): string {
+ return email.includes('<') ? email : `<${email}>`;
+}
+```
+
+---
+
+### Rate Limiting
+
+**429 Too Many Requests**
+
+Error:
+```json
+{
+ "data": {
+ "error": "Rate limit exceeded",
+ "error_code": "E_ApiResponseCodes_RATE_LIMIT_EXCEEDED"
+ }
+}
+```
+
+Fix: SMTP2Go allows 10 requests/second. Implement throttling.
+
+---
+
+## Cross-Provider Error Patterns
+
+### Domain Not Verified
+
+All providers require domain verification. Steps:
+
+1. **Add domain** in provider dashboard
+2. **Add DNS records**:
+ - SPF: `v=spf1 include:_spf.provider.com ~all`
+ - DKIM: `<selector>._domainkey TXT <value>`
+ - DMARC: `_dmarc TXT v=DMARC1; p=none;`
+3. **Wait for verification** (15 minutes to 48 hours)
+4. **Test** with provider's verification tool
+
+---
+
+### Invalid Email Format
+
+All providers reject malformed emails. Validate before sending:
+
+```typescript
+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+function validateEmail(email: string): boolean {
+ if (!EMAIL_REGEX.test(email)) return false;
+
+ // Additional checks
+ if (email.length > 254) return false; // RFC 5321
+ const [local, domain] = email.split('@');
+ if (local.length > 64) return false; // RFC 5321
+ if (domain.length > 253) return false; // RFC 1035
+
+ return true;
+}
+```
+
+---
+
+### Rate Limit Exceeded
+
+All providers have rate limits. Use exponential backoff:
+
+```typescript
+async function sendWithBackoff(
+ sendFn: () => Promise<Response>,
+ maxRetries = 5
+): Promise<Response> {
+ let lastError: Error | null = null;
+
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ try {
+ const response = await sendFn();
+
+ if (response.status === 429) {
+ const retryAfter = response.headers.get('Retry-After');
+ const delay = retryAfter
+ ? parseInt(retryAfter) * 1000
+ : Math.pow(2, attempt) * 1000;
+
+ console.log(`Rate limited. Retrying in ${delay}ms...`);
+ await new Promise(resolve => setTimeout(resolve, delay));
+ continue;
+ }
+
+ if (response.status >= 500) {
+ const delay = Math.pow(2, attempt) * 1000;
+ console.log(`Server error. Retrying in ${delay}ms...`);
+ await new Promise(resolve => setTimeout(resolve, delay));
+ continue;
+ }
+
+ return response;
+ } catch (error) {
+ lastError = error as Error;
+ if (attempt < maxRetries - 1) {
+ const delay = Math.pow(2, attempt) * 1000;
+ await new Promise(resolve => setTimeout(resolve, delay));
+ }
+ }
+ }
+
+ throw lastError || new Error('Max retries exceeded');
+}
+```
+
+---
+
+### Attachment Size Exceeded
+
+All providers have attachment size limits:
+- Resend: 40 MB total
+- SendGrid: 20 MB total
+- Mailgun: 25 MB total
+- SMTP2Go: 50 MB total
+
+For large files, host externally:
+
+```typescript
+async function sendWithLargeFile(
+ to: string,
+ subject: string,
+ html: string,
+ file: File,
+ env: Env
+) {
+ const MAX_SIZE = 20 * 1024 * 1024; // 20 MB for SendGrid
+
+ if (file.size > MAX_SIZE) {
+ // Upload to R2/S3
+ const fileUrl = await env.R2.put(`files/${file.name}`, file);
+ const signedUrl = await generateSignedUrl(fileUrl);
+
+ // Send link instead
+ html += `<p><a href="${signedUrl}">Download ${file.name}</a></p>`;
+ return sendEmail(to, subject, html, env);
+ }
+
+ // Send with attachment
+ const base64 = await fileToBase64(file);
+ return sendEmailWithAttachment(to, subject, html, base64, file.name, env);
+}
+```
+
+---
+
+## Debugging Tips
+
+### Enable Verbose Logging
+
+```typescript
+async function sendEmailWithLogging(email: any, env: Env) {
+ console.log('Sending email:', JSON.stringify(email, null, 2));
+
+ const response = await fetch(endpoint, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(email),
+ });
+
+ console.log('Response status:', response.status);
+ console.log('Response headers:', Object.fromEntries(response.headers.entries()));
+
+ const body = await response.text();
+ console.log('Response body:', body);
+
+ return response;
+}
+```
+
+---
+
+### Test in Development
+
+Use provider test modes:
+
+**Resend**: Use test API key (starts with `re_test_`)
+**SendGrid**: Use Sandbox Mode (set `mail_settings.sandbox_mode.enable: true`)
+**Mailgun**: Send to `@sandbox[domain].mailgun.org`
+**SMTP2Go**: Use test mode in dashboard
+
+---
+
+### Monitor Error Rates
+
+Track errors in D1:
+
+```typescript
+await env.DB.prepare(`
+ INSERT INTO email_errors (provider, error_code, error_message, timestamp)
+ VALUES (?, ?, ?, ?)
+`).bind(provider, error.code, error.message, Date.now()).run();
+```
+
+Alert when error rate exceeds threshold.
+
+---
+
+## Summary
+
+- **Verify domains** before production
+- **Validate email addresses** before sending
+- **Implement exponential backoff** for retries
+- **Monitor error rates** and alert on anomalies
+- **Handle provider-specific quirks** (e.g., SMTP2Go angle brackets)
+- **Use test modes** during development
+- **Log verbosely** for debugging
diff --git a/skills/email-gateway/references/provider-comparison.md b/skills/email-gateway/references/provider-comparison.md
new file mode 100644
index 00000000..9cbbd348
--- /dev/null
+++ b/skills/email-gateway/references/provider-comparison.md
@@ -0,0 +1,337 @@
+# Email Provider Comparison
+
+Comprehensive comparison of Resend, SendGrid, Mailgun, and SMTP2Go for transactional email.
+
+## Quick Decision Matrix
+
+| Your Needs | Best Provider | Reason |
+|------------|---------------|--------|
+| React Email, modern DX | **Resend** | Native JSX support, simple API |
+| Enterprise scale (1M+/mo) | **SendGrid** | Advanced analytics, A/B testing |
+| Developer webhooks, flexibility | **Mailgun** | Detailed events, template engine |
+| Simple relay, AU-based | **SMTP2Go** | Reliable, good support |
+| Starting out, small app | **Resend** or **SendGrid** | Both have generous free tiers |
+| Budget-conscious (<$50/mo) | **Resend** | Best value at scale |
+
+---
+
+## Detailed Comparison
+
+### Pricing (as of 2026)
+
+| Provider | Free Tier | Entry Paid | Scale ($90-100/mo) |
+|----------|-----------|------------|-------------------|
+| **Resend** | 100/day, 3k/mo | $20 for 50k | $80 for 500k |
+| **SendGrid** | 100/day forever | $15 for 10k | $90 for 100k |
+| **Mailgun** | 100/day forever | $15 for 10k | $90 for 100k |
+| **SMTP2Go** | 1k trial | $10 for 10k | $80 for 100k |
+
+**Best Value**: Resend (500k emails for $80 vs competitors' 100k)
+
+---
+
+### Features
+
+#### Email Composition
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| HTML Email | ✅ | ✅ | ✅ | ✅ |
+| Plain Text | ✅ | ✅ | ✅ | ✅ |
+| React Email (JSX) | ✅ Native | ❌ | ❌ | ❌ |
+| Dynamic Templates | ✅ | ✅ | ✅ | ✅ |
+| Template Builder | Dashboard | Visual editor | Dashboard | Dashboard |
+| Template Versioning | ✅ | ✅ | ✅ | Limited |
+
+**Winner**: Resend (React Email is game-changing for developers)
+
+#### Delivery Features
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| Batch Sending | 50/req | 1000/req | 1000/req | 100/req |
+| Scheduled Send | ✅ | ✅ | ✅ | ❌ |
+| SMTP Relay | ✅ | ✅ | ✅ | ✅ Primary |
+| Dedicated IPs | Enterprise | $90+/mo | $80+/mo | Custom |
+| IP Warmup | Managed | Manual | Manual | Managed |
+| Custom Domains | ✅ | ✅ | ✅ | ✅ |
+
+**Winner**: SendGrid/Mailgun (better batch capabilities)
+
+#### Analytics & Tracking
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| Open Tracking | ✅ | ✅ | ✅ | ✅ |
+| Click Tracking | ✅ | ✅ | ✅ | ✅ |
+| Bounce Handling | ✅ | ✅ | ✅ | ✅ |
+| Spam Reports | ✅ | ✅ | ✅ | ✅ |
+| Dashboard Analytics | Basic | Advanced | Advanced | Good |
+| A/B Testing | ❌ | ✅ | ✅ | ❌ |
+| Engagement Insights | Basic | Advanced | Advanced | Basic |
+
+**Winner**: SendGrid (most comprehensive analytics)
+
+#### Developer Experience
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| API Simplicity | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
+| Documentation | Excellent | Good | Excellent | Good |
+| SDKs | 10+ languages | 7 languages | 8 languages | 4 languages |
+| Webhooks | ✅ 6 events | ✅ 15+ events | ✅ 12+ events | ✅ 8 events |
+| Webhook Verification | ✅ HMAC | ✅ ECDSA | ✅ HMAC | ✅ HMAC |
+| API Rate Limits | 10/sec | 600/sec | Varies | 10/sec |
+
+**Winner**: Resend (simplest API) / Mailgun (most detailed webhooks)
+
+#### Support & Reliability
+
+| Feature | Resend | SendGrid | Mailgun | SMTP2Go |
+|---------|--------|----------|---------|---------|
+| Free Tier Support | Email | Email | Ticket | Email |
+| Paid Support | Email/Slack | Chat/Phone | Email/Chat | Email/Phone |
+| SLA | 99.9% (paid) | 99.9% (paid) | 99.9% (paid) | 99.9% |
+| Status Page | ✅ | ✅ | ✅ | ✅ |
+| Region Options | Global | Global | US/EU | AU-focused |
+
+**Winner**: Tie (all have good uptime, SMTP2Go best for AU)
+
+---
+
+## Use Case Recommendations
+
+### Modern SaaS App (React/Next.js)
+
+**Choose: Resend**
+
+Why:
+- React Email integration
+- Simple API
+- Best pricing at scale
+- Modern developer experience
+
+Example:
+```typescript
+await resend.emails.send({
+ subject: 'Welcome!',
+ react: WelcomeEmail({ name: 'Alice' }),
+});
+```
+
+---
+
+### Enterprise Email (1M+/month)
+
+**Choose: SendGrid**
+
+Why:
+- Advanced analytics
+- A/B testing
+- Proven at scale
+- Phone support
+
+Example:
+```typescript
+// Batch 1000 personalized emails
+personalizations: users.map(u => ({
+ to: [{ email: u.email }],
+ dynamic_template_data: { name: u.name },
+}))
+```
+
+---
+
+### Developer Tools / Webhooks-Heavy
+
+**Choose: Mailgun**
+
+Why:
+- Detailed webhook events
+- Flexible template variables
+- Developer-friendly API
+- Good documentation
+
+Example:
+```typescript
+// Track every email event
+events: ['delivered', 'opened', 'clicked', 'failed', 'complained']
+```
+
+---
+
+### Simple Transactional (Australia)
+
+**Choose: SMTP2Go**
+
+Why:
+- AU-based (low latency)
+- Simple, reliable
+- Good support
+- Affordable
+
+Example:
+```typescript
+// Just works, no fuss
+{
+ api_key: env.SMTP2GO_API_KEY,
+ to: ['<[email protected]>'],
+ sender: '[email protected]',
+ subject: 'Welcome',
+ html_body: '<h1>Hello</h1>',
+}
+```
+
+---
+
+## Migration Considerations
+
+### From SendGrid to Resend
+
+**Why migrate:**
+- Lower cost at scale
+- Better DX
+- React Email support
+
+**Migration path:**
+1. Set up Resend account, verify domain
+2. Convert dynamic templates to React components or HTML
+3. Update API calls (simple structure change)
+4. Switch DNS/webhooks
+5. Monitor deliverability for 1 week
+6. Cancel SendGrid
+
+**Gotchas:**
+- Batch size drops from 1000 to 50 per request
+- Template syntax changes (handlebars → React)
+- Webhook events slightly different
+
+---
+
+### From Mailgun to Resend
+
+**Why migrate:**
+- Simpler API
+- React Email
+- Better pricing
+
+**Migration path:**
+1. Verify domain in Resend
+2. Convert Mailgun templates to React or HTML
+3. Update FormData API calls to JSON
+4. Update webhook handlers (different signature verification)
+5. Switch DNS
+6. Monitor for 1 week
+
+**Gotchas:**
+- No more FormData (use JSON body)
+- Template variables format changes
+- Webhook signature verification method different
+
+---
+
+### From Resend to SendGrid
+
+**Why migrate:**
+- Need A/B testing
+- Need advanced analytics
+- Larger batch sizes
+
+**Migration path:**
+1. Set up SendGrid, verify domain
+2. Convert React Email to dynamic templates (or render to HTML)
+3. Update API calls (more complex structure)
+4. Set up webhook handlers
+5. Switch DNS
+6. Monitor deliverability
+
+**Gotchas:**
+- More complex API structure
+- Template builder less developer-friendly
+- React Email requires pre-rendering
+
+---
+
+## Technical Comparison
+
+### API Request Format
+
+**Resend** (Simple JSON):
+```json
+{
+ "from": "[email protected]",
+ "subject": "Welcome",
+ "html": "<h1>Hello</h1>"
+}
+```
+
+**SendGrid** (Nested JSON):
+```json
+{
+ "personalizations": [{
+ "to": [{ "email": "[email protected]" }]
+ }],
+ "from": { "email": "[email protected]" },
+ "subject": "Welcome",
+ "content": [{
+ "type": "text/html",
+ "value": "<h1>Hello</h1>"
+ }]
+}
+```
+
+**Mailgun** (FormData):
+```
+subject: Welcome
+html: <h1>Hello</h1>
+```
+
+**SMTP2Go** (JSON with angle brackets):
+```json
+{
+ "api_key": "...",
+ "to": ["<[email protected]>"],
+ "sender": "[email protected]",
+ "subject": "Welcome",
+ "html_body": "<h1>Hello</h1>"
+}
+```
+
+---
+
+### Webhook Event Names
+
+| Event | Resend | SendGrid | Mailgun | SMTP2Go |
+|-------|--------|----------|---------|---------|
+| Delivered | `email.delivered` | `delivered` | `delivered` | `delivered` |
+| Bounced | `email.bounced` | `bounce` | `failed` | `bounce` |
+| Spam | `email.complained` | `spamreport` | `complained` | `spam` |
+| Opened | `email.opened` | `open` | `opened` | `open` |
+| Clicked | `email.clicked` | `click` | `clicked` | `click` |
+
+---
+
+### Rate Limits
+
+| Provider | Requests/sec | Burst | Emails/day (Free) |
+|----------|--------------|-------|-------------------|
+| Resend | 10 | Yes | 100 |
+| SendGrid | 600 | Yes | 100 |
+| Mailgun | Varies | Yes | 100 |
+| SMTP2Go | 10 | Limited | ~33 (1k/mo trial) |
+
+---
+
+## Summary
+
+**Best Overall**: **Resend** (modern, simple, best value)
+**Best for Enterprise**: **SendGrid** (scale, analytics, support)
+**Best for Developers**: **Mailgun** (webhooks, flexibility)
+**Best for Australia**: **SMTP2Go** (local, reliable)
+
+Choose based on your specific needs and priorities.
diff --git a/skills/email-gateway/references/rate-limits.md b/skills/email-gateway/references/rate-limits.md
new file mode 100644
index 00000000..da3ce3b5
--- /dev/null
+++ b/skills/email-gateway/references/rate-limits.md
@@ -0,0 +1,444 @@
+# Rate Limits & Quotas
+
+Comprehensive rate limiting reference for all four email providers.
+
+## Rate Limits by Provider
+
+### Resend
+
+| Tier | Daily Limit | Monthly Limit | API Rate | Burst |
+|------|-------------|---------------|----------|-------|
+| Free | 100 | 3,000 | 10 req/sec | Yes |
+| Paid ($20) | Unlimited | 50,000 | 10 req/sec | Yes |
+| Scale ($80) | Unlimited | 500,000 | 50 req/sec | Yes |
+
+**Batch Size**: 50 recipients per request
+
+**Response Headers**:
+- `X-RateLimit-Limit`: Maximum requests
+- `X-RateLimit-Remaining`: Requests remaining
+- `X-RateLimit-Reset`: Unix timestamp for reset
+- `Retry-After`: Seconds to wait (on 429)
+
+**Burst Handling**: Short bursts above limit are tolerated
+
+**Overage Cost**: $1 per 1,000 emails
+
+---
+
+### SendGrid
+
+| Tier | Daily Limit | Monthly Limit | API Rate | Burst |
+|------|-------------|---------------|----------|-------|
+| Free | 100 | Forever | 600 req/sec | Yes |
+| Basic ($15) | Unlimited | 10,000 | 600 req/sec | Yes |
+| Foundation ($35) | Unlimited | 50,000 | 600 req/sec | Yes |
+| Scale ($90) | Unlimited | 100,000 | 600 req/sec | Yes |
+
+**Batch Size**: 1,000 recipients per request (via personalizations)
+
+**Response Headers**:
+- `X-RateLimit-Limit`: 600
+- `X-RateLimit-Remaining`: Requests remaining
+- `X-RateLimit-Reset`: Unix timestamp
+
+**Burst Handling**: Allows bursts up to 6,000 requests in 10 seconds
+
+**Overage Cost**: $1.80-$1.10 per 1,000 emails (tier-dependent)
+
+---
+
+### Mailgun
+
+| Tier | Daily Limit | Monthly Limit | API Rate | Burst |
+|------|-------------|---------------|----------|-------|
+| Free | 100 | Forever | Varies | Limited |
+| Basic ($15) | Unlimited | 10,000 | 100 req/sec | Yes |
+| Foundation ($35) | Unlimited | 50,000 | 300 req/sec | Yes |
+| Scale ($90) | Unlimited | 100,000 | 1,000 req/sec | Yes |
+
+**Batch Size**: 1,000 recipients per request
+
+**Response Headers**:
+- `X-RateLimit-Limit`: Tier-specific
+- `X-RateLimit-Remaining`: Requests remaining
+- `X-RateLimit-Reset`: Unix timestamp
+- `Retry-After`: Seconds to wait (on 429)
+
+**Burst Handling**: Short bursts tolerated on paid plans
+
+**Overage Cost**: $1.30-$1.10 per 1,000 emails (tier-dependent)
+
+---
+
+### SMTP2Go
+
+| Tier | Daily Limit | Monthly Limit | API Rate | Burst |
+|------|-------------|---------------|----------|-------|
+| Trial | ~33 | 1,000 | 10 req/sec | Limited |
+| Basic ($10) | Unlimited | 10,000 | 10 req/sec | Limited |
+| Standard ($35) | Unlimited | 50,000 | 10 req/sec | Limited |
+| Pro ($80) | Unlimited | 100,000 | 10 req/sec | Limited |
+
+**Batch Size**: 100 recipients per request
+
+**Response Headers**:
+- `X-RateLimit-Limit`: 10
+- `X-RateLimit-Remaining`: Requests remaining
+- `Retry-After`: Seconds to wait (on 429)
+
+**Burst Handling**: Limited burst capacity
+
+**Overage Cost**: Varies by tier (~$1 per 1,000)
+
+---
+
+## Rate Limiting Implementation
+
+### Simple Token Bucket (KV-based)
+
+```typescript
+interface RateLimitConfig {
+ maxRequests: number;
+ windowSeconds: number;
+}
+
+async function checkRateLimit(
+ key: string,
+ config: RateLimitConfig,
+ kv: KVNamespace
+): Promise<{ allowed: boolean; resetAt?: number }> {
+ const now = Date.now();
+ const stateKey = `rate-limit:${key}`;
+ const stateJson = await kv.get(stateKey);
+
+ if (!stateJson) {
+ // First request in window
+ const state = {
+ count: 1,
+ resetAt: now + config.windowSeconds * 1000,
+ };
+ await kv.put(stateKey, JSON.stringify(state), { expirationTtl: config.windowSeconds });
+ return { allowed: true };
+ }
+
+ const state = JSON.parse(stateJson);
+
+ if (now > state.resetAt) {
+ // Window expired, reset
+ const newState = {
+ count: 1,
+ resetAt: now + config.windowSeconds * 1000,
+ };
+ await kv.put(stateKey, JSON.stringify(newState), { expirationTtl: config.windowSeconds });
+ return { allowed: true };
+ }
+
+ if (state.count >= config.maxRequests) {
+ // Rate limit exceeded
+ return { allowed: false, resetAt: state.resetAt };
+ }
+
+ // Increment count
+ state.count++;
+ await kv.put(stateKey, JSON.stringify(state), { expirationTtl: config.windowSeconds });
+ return { allowed: true };
+}
+
+// Usage
+const limit = await checkRateLimit('user:123', { maxRequests: 10, windowSeconds: 1 }, env.KV);
+if (!limit.allowed) {
+ return new Response('Rate limit exceeded', {
+ status: 429,
+ headers: {
+ 'Retry-After': String(Math.ceil((limit.resetAt! - Date.now()) / 1000)),
+ },
+ });
+}
+```
+
+---
+
+### Durable Objects Rate Limiter
+
+```typescript
+// rate-limiter.ts
+export class RateLimiter {
+ private state: DurableObjectState;
+ private counts: Map<string, { count: number; resetAt: number }> = new Map();
+
+ constructor(state: DurableObjectState) {
+ this.state = state;
+ }
+
+ async fetch(request: Request): Promise<Response> {
+ const { key, maxRequests, windowMs } = await request.json();
+
+ const now = Date.now();
+ const current = this.counts.get(key);
+
+ if (!current || now > current.resetAt) {
+ this.counts.set(key, { count: 1, resetAt: now + windowMs });
+ return new Response(JSON.stringify({ allowed: true }));
+ }
+
+ if (current.count >= maxRequests) {
+ return new Response(JSON.stringify({
+ allowed: false,
+ resetAt: current.resetAt,
+ }));
+ }
+
+ current.count++;
+ this.counts.set(key, current);
+ return new Response(JSON.stringify({ allowed: true }));
+ }
+}
+
+// Usage in Worker
+const id = env.RATE_LIMITER.idFromName('email-limits');
+const stub = env.RATE_LIMITER.get(id);
+const response = await stub.fetch('http://internal/check', {
+ method: 'POST',
+ body: JSON.stringify({
+ key: `user:${userId}`,
+ maxRequests: 10,
+ windowMs: 1000,
+ }),
+});
+
+const { allowed, resetAt } = await response.json();
+if (!allowed) {
+ return new Response('Rate limit exceeded', { status: 429 });
+}
+```
+
+---
+
+### Per-Provider Rate Limiting
+
+```typescript
+const PROVIDER_LIMITS: Record<string, RateLimitConfig> = {
+ resend: { maxRequests: 10, windowSeconds: 1 },
+ sendgrid: { maxRequests: 600, windowSeconds: 1 },
+ mailgun: { maxRequests: 100, windowSeconds: 1 },
+ smtp2go: { maxRequests: 10, windowSeconds: 1 },
+};
+
+async function sendEmailRateLimited(
+ provider: 'resend' | 'sendgrid' | 'mailgun' | 'smtp2go',
+ email: any,
+ env: Env
+) {
+ const limit = await checkRateLimit(
+ `provider:${provider}`,
+ PROVIDER_LIMITS[provider],
+ env.KV
+ );
+
+ if (!limit.allowed) {
+ const waitMs = limit.resetAt! - Date.now();
+ await new Promise(resolve => setTimeout(resolve, waitMs));
+ }
+
+ return sendEmail(provider, email, env);
+}
+```
+
+---
+
+## Quota Management
+
+### Track Usage
+
+```typescript
+// Increment quota on each send
+async function trackEmailSent(userId: string, env: Env) {
+ const month = new Date().toISOString().slice(0, 7); // YYYY-MM
+ const key = `quota:${userId}:${month}`;
+
+ const current = await env.KV.get(key);
+ const count = current ? parseInt(current) + 1 : 1;
+
+ await env.KV.put(key, String(count), {
+ expirationTtl: 60 * 60 * 24 * 32, // 32 days
+ });
+
+ return count;
+}
+
+// Check quota before sending
+async function checkQuota(userId: string, plan: 'free' | 'pro', env: Env) {
+ const limits = { free: 1000, pro: 50000 };
+ const month = new Date().toISOString().slice(0, 7);
+ const key = `quota:${userId}:${month}`;
+
+ const current = await env.KV.get(key);
+ const count = current ? parseInt(current) : 0;
+
+ return {
+ used: count,
+ limit: limits[plan],
+ remaining: limits[plan] - count,
+ exceeded: count >= limits[plan],
+ };
+}
+```
+
+---
+
+### Quota Exceeded Response
+
+```typescript
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const userId = getUserId(request);
+ const plan = await getUserPlan(userId, env);
+
+ const quota = await checkQuota(userId, plan, env);
+ if (quota.exceeded) {
+ return new Response(JSON.stringify({
+ error: 'Monthly quota exceeded',
+ used: quota.used,
+ limit: quota.limit,
+ resetDate: getNextMonth(),
+ }), {
+ status: 429,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ await sendEmail(request, env);
+ await trackEmailSent(userId, env);
+
+ return new Response(JSON.stringify({ success: true }));
+ },
+};
+```
+
+---
+
+## Burst Handling
+
+### Cloudflare Queues for Burst Absorption
+
+```typescript
+// Producer (API endpoint)
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const email = await request.json();
+
+ // Queue email instead of sending immediately
+ await env.EMAIL_QUEUE.send(email);
+
+ return new Response(JSON.stringify({ queued: true }));
+ },
+};
+
+// Consumer (rate-limited sender)
+export default {
+ async queue(batch: MessageBatch<any>, env: Env): Promise<void> {
+ for (const message of batch.messages) {
+ const email = message.body;
+
+ // Rate-limited send
+ const limit = await checkRateLimit('provider:resend', { maxRequests: 10, windowSeconds: 1 }, env.KV);
+ if (!limit.allowed) {
+ const waitMs = limit.resetAt! - Date.now();
+ await new Promise(resolve => setTimeout(resolve, waitMs));
+ }
+
+ await sendEmail(email, env);
+ message.ack();
+ }
+ },
+};
+```
+
+---
+
+## Multi-Provider Failover
+
+Route to different providers based on quota/rate limits:
+
+```typescript
+async function sendWithFailover(email: any, env: Env) {
+ const providers: Array<'resend' | 'sendgrid' | 'mailgun' | 'smtp2go'> = [
+ 'resend',
+ 'sendgrid',
+ 'mailgun',
+ 'smtp2go',
+ ];
+
+ for (const provider of providers) {
+ const limit = await checkRateLimit(
+ `provider:${provider}`,
+ PROVIDER_LIMITS[provider],
+ env.KV
+ );
+
+ if (limit.allowed) {
+ try {
+ return await sendEmail(provider, email, env);
+ } catch (error) {
+ console.error(`${provider} failed:`, error);
+ continue;
+ }
+ }
+ }
+
+ throw new Error('All providers rate limited or failed');
+}
+```
+
+---
+
+## Monitoring & Alerts
+
+### Track Rate Limit Hits
+
+```typescript
+async function logRateLimitHit(provider: string, env: Env) {
+ await env.DB.prepare(`
+ INSERT INTO rate_limit_hits (provider, timestamp)
+ VALUES (?, ?)
+ `).bind(provider, Date.now()).run();
+}
+
+// Alert if rate limit hits exceed threshold
+const hits = await env.DB.prepare(`
+ SELECT COUNT(*) as count FROM rate_limit_hits
+ WHERE provider = ? AND timestamp > ?
+`).bind(provider, Date.now() - 60000).first(); // Last minute
+
+if (hits.count > 10) {
+ await sendSlackAlert({
+ text: `⚠️ ${provider} rate limit hit ${hits.count} times in last minute`,
+ });
+}
+```
+
+---
+
+## Best Practices
+
+1. **Use Queues**: Absorb bursts with Cloudflare Queues
+2. **Implement Backoff**: Exponential backoff on 429 responses
+3. **Track Quotas**: Monitor usage vs limits
+4. **Multi-Provider**: Failover to alternate providers
+5. **Alert Early**: Notify when approaching limits
+6. **Batch When Possible**: Use provider batch capabilities
+7. **Respect Retry-After**: Honor provider retry headers
+
+---
+
+## Summary
+
+| Provider | Best For | Rate Limit | Batch Size |
+|----------|----------|------------|------------|
+| Resend | Low-volume, bursts ok | 10/sec | 50 |
+| SendGrid | High-volume enterprise | 600/sec | 1,000 |
+| Mailgun | Medium-volume flexible | 100/sec | 1,000 |
+| SMTP2Go | Low-volume reliable | 10/sec | 100 |
+
+Choose based on your sending patterns and volume requirements.
diff --git a/skills/email-gateway/references/webhook-events.md b/skills/email-gateway/references/webhook-events.md
new file mode 100644
index 00000000..6c5c35dc
--- /dev/null
+++ b/skills/email-gateway/references/webhook-events.md
@@ -0,0 +1,479 @@
+# Webhook Events Reference
+
+Complete guide to webhook events for all four email providers.
+
+## Event Types by Provider
+
+### Resend Webhook Events
+
+| Event | Trigger | Typical Action |
+|-------|---------|----------------|
+| `email.sent` | Email accepted by Resend | Log timestamp |
+| `email.delivered` | Email delivered to recipient | Update delivery status |
+| `email.delivery_delayed` | Temporary delivery issue | Alert if >1 hour |
+| `email.bounced` | Permanent delivery failure | Mark email invalid |
+| `email.complained` | Spam complaint | Unsubscribe immediately |
+| `email.opened` | Recipient opened email | Track engagement |
+| `email.clicked` | Recipient clicked link | Track conversion |
+
+**Signature Verification**: HMAC SHA-256 (Svix format)
+
+Headers:
+- `svix-id`: Message ID
+- `svix-timestamp`: Unix timestamp
+- `svix-signature`: HMAC signature
+
+Example payload:
+```json
+{
+ "type": "email.delivered",
+ "created_at": "2026-01-10T12:00:00Z",
+ "data": {
+ "email_id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794",
+ "from": "[email protected]",
+ "to": ["[email protected]"],
+ "subject": "Welcome!",
+ "created_at": "2026-01-10T11:59:00Z"
+ }
+}
+```
+
+---
+
+### SendGrid Webhook Events
+
+| Event | Trigger | Typical Action |
+|-------|---------|----------------|
+| `processed` | Email processed by SendGrid | Log initial processing |
+| `dropped` | Email dropped (invalid, duplicate) | Alert, investigate |
+| `delivered` | Email delivered successfully | Update status |
+| `bounce` | Hard/soft bounce | Mark email invalid if hard |
+| `deferred` | Temporary delivery delay | Monitor |
+| `open` | Email opened (tracking pixel) | Track engagement |
+| `click` | Link clicked | Track conversion |
+| `spamreport` | Marked as spam | Unsubscribe, review content |
+| `unsubscribe` | Unsubscribe link clicked | Unsubscribe user |
+| `group_unsubscribe` | Unsubscribed from group | Update preferences |
+| `group_resubscribe` | Resubscribed to group | Update preferences |
+
+**Signature Verification**: ECDSA with public key
+
+Headers:
+- `X-Twilio-Email-Event-Webhook-Signature`: Base64 encoded signature
+- `X-Twilio-Email-Event-Webhook-Timestamp`: Unix timestamp
+
+Example payload (array of events):
+```json
+[
+ {
+ "email": "[email protected]",
+ "timestamp": 1736508000,
+ "smtp-id": "<[email protected]>",
+ "event": "delivered",
+ "category": ["welcome"],
+ "sg_event_id": "abc123...",
+ "sg_message_id": "def456..."
+ }
+]
+```
+
+---
+
+### Mailgun Webhook Events
+
+| Event | Trigger | Typical Action |
+|-------|---------|----------------|
+| `accepted` | Email accepted by Mailgun | Log acceptance |
+| `rejected` | Email rejected (invalid) | Alert, fix sender config |
+| `delivered` | Email delivered successfully | Update status |
+| `failed` | Permanent/temporary failure | Mark invalid if permanent |
+| `opened` | Email opened | Track engagement |
+| `clicked` | Link clicked | Track conversion |
+| `unsubscribed` | Unsubscribe link clicked | Unsubscribe user |
+| `complained` | Spam complaint | Unsubscribe immediately |
+| `stored` | Email stored (for retrieval) | Optional archival |
+
+**Signature Verification**: HMAC SHA-256
+
+Fields in payload:
+- `signature.timestamp`: Unix timestamp
+- `signature.token`: Random token
+- `signature.signature`: HMAC hash
+
+Example payload:
+```json
+{
+ "signature": {
+ "timestamp": "1736508000",
+ "token": "abc123...",
+ "signature": "def456..."
+ },
+ "event-data": {
+ "event": "delivered",
+ "timestamp": 1736508000.123,
+ "id": "xyz789...",
+ "recipient": "[email protected]",
+ "message": {
+ "headers": {
+ "message-id": "<[email protected]>",
+ "from": "[email protected]",
+ "subject": "Welcome!"
+ }
+ },
+ "tags": ["welcome"],
+ "user-variables": {
+ "user_id": "12345"
+ }
+ }
+}
+```
+
+---
+
+### SMTP2Go Webhook Events
+
+| Event | Trigger | Typical Action |
+|-------|---------|----------------|
+| `delivered` | Email delivered successfully | Update status |
+| `bounce` | Hard/soft bounce | Mark email invalid if hard |
+| `spam` | Spam complaint | Unsubscribe immediately |
+| `open` | Email opened | Track engagement |
+| `click` | Link clicked | Track conversion |
+| `unsubscribe` | Unsubscribe link clicked | Unsubscribe user |
+| `suppress` | Email suppressed (blocklist) | Alert, investigate |
+| `error` | Send error | Alert, investigate |
+
+**Signature Verification**: HMAC SHA-256
+
+Headers:
+- `X-Smtp2go-Signature`: Hex-encoded HMAC signature
+
+Example payload:
+```json
+{
+ "event": "delivered",
+ "email_id": "abc123...",
+ "email": "[email protected]",
+ "timestamp": 1736508000,
+ "subject": "Welcome!",
+ "message_id": "<[email protected]>"
+}
+```
+
+---
+
+## Webhook Security
+
+### Resend Signature Verification
+
+```typescript
+import { createHmac } from 'crypto';
+
+function verifyResendWebhook(
+ request: Request,
+ secret: string
+): boolean {
+ const signature = request.headers.get('svix-signature');
+ const timestamp = request.headers.get('svix-timestamp');
+ const body = await request.text();
+
+ if (!signature || !timestamp) return false;
+
+ const signedContent = `${timestamp}.${body}`;
+ const expectedSignature = createHmac('sha256', secret)
+ .update(signedContent)
+ .digest('base64');
+
+ return signature.includes(expectedSignature);
+}
+```
+
+---
+
+### SendGrid Signature Verification
+
+```typescript
+import { EventWebhook, EventWebhookHeader } from '@sendgrid/eventwebhook';
+
+function verifySendGridWebhook(
+ request: Request,
+ publicKey: string
+): boolean {
+ const signature = request.headers.get(EventWebhookHeader.SIGNATURE());
+ const timestamp = request.headers.get(EventWebhookHeader.TIMESTAMP());
+ const body = await request.text();
+
+ const eventWebhook = new EventWebhook();
+ const ecPublicKey = eventWebhook.convertPublicKeyToECDSA(publicKey);
+
+ return eventWebhook.verifySignature(
+ ecPublicKey,
+ body,
+ signature!,
+ timestamp!
+ );
+}
+```
+
+---
+
+### Mailgun Signature Verification
+
+```typescript
+import { createHmac } from 'crypto';
+
+function verifyMailgunWebhook(
+ timestamp: string,
+ token: string,
+ signature: string,
+ signingKey: string
+): boolean {
+ const encoded = createHmac('sha256', signingKey)
+ .update(`${timestamp}${token}`)
+ .digest('hex');
+
+ return encoded === signature;
+}
+```
+
+---
+
+### SMTP2Go Signature Verification
+
+```typescript
+import { createHmac } from 'crypto';
+
+function verifySMTP2GoWebhook(
+ body: string,
+ signature: string,
+ secret: string
+): boolean {
+ const expectedSignature = createHmac('sha256', secret)
+ .update(body)
+ .digest('hex');
+
+ return expectedSignature === signature;
+}
+```
+
+---
+
+## Common Webhook Patterns
+
+### Handle Bounces
+
+```typescript
+async function handleBounce(email: string, severity: 'permanent' | 'temporary') {
+ if (severity === 'permanent') {
+ // Hard bounce - mark email as invalid
+ await db.prepare(`
+ UPDATE users SET email_valid = 0 WHERE email = ?
+ `).bind(email).run();
+
+ console.log(`Marked email as invalid: ${email}`);
+ } else {
+ // Soft bounce - track but don't invalidate yet
+ await db.prepare(`
+ INSERT INTO email_bounces (email, severity, bounced_at)
+ VALUES (?, ?, ?)
+ `).bind(email, severity, Date.now()).run();
+
+ console.log(`Soft bounce tracked: ${email}`);
+ }
+}
+```
+
+---
+
+### Handle Spam Complaints
+
+```typescript
+async function handleSpamComplaint(email: string) {
+ // Immediately unsubscribe
+ await db.prepare(`
+ UPDATE users SET subscribed = 0, spam_complained = 1 WHERE email = ?
+ `).bind(email).run();
+
+ // Alert team
+ await sendSlackAlert({
+ channel: '#email-alerts',
+ text: `⚠️ Spam complaint from ${email}`,
+ });
+
+ console.log(`Unsubscribed due to spam complaint: ${email}`);
+}
+```
+
+---
+
+### Track Engagement
+
+```typescript
+async function trackEmailOpen(email: string, messageId: string) {
+ await db.prepare(`
+ INSERT INTO email_opens (email, message_id, opened_at)
+ VALUES (?, ?, ?)
+ `).bind(email, messageId, Date.now()).run();
+
+ console.log(`Email opened: ${email}`);
+}
+
+async function trackEmailClick(email: string, messageId: string, url: string) {
+ await db.prepare(`
+ INSERT INTO email_clicks (email, message_id, url, clicked_at)
+ VALUES (?, ?, ?, ?)
+ `).bind(email, messageId, url, Date.now()).run();
+
+ console.log(`Link clicked: ${email} -> ${url}`);
+}
+```
+
+---
+
+## Webhook Testing
+
+### Test Webhook Locally (ngrok)
+
+```bash
+# Install ngrok
+brew install ngrok
+
+# Start your Worker locally
+npm run dev
+
+# Create tunnel
+ngrok http 8787
+
+# Use ngrok URL in provider webhook settings
+https://abc123.ngrok.io/webhook
+```
+
+---
+
+### Test Webhook Signature Verification
+
+```typescript
+// Test Resend webhook
+const testPayload = {
+ type: 'email.delivered',
+ data: { email_id: 'test-123' },
+};
+
+const secret = 'whsec_test...';
+const timestamp = String(Date.now());
+const body = JSON.stringify(testPayload);
+const signature = createHmac('sha256', secret)
+ .update(`${timestamp}.${body}`)
+ .digest('base64');
+
+console.log('Signature:', signature);
+console.log('Use this in X-Svix-Signature header');
+```
+
+---
+
+## Webhook Best Practices
+
+### 1. Return 200 Quickly
+
+Process webhooks asynchronously:
+
+```typescript
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ // Verify signature first
+ const isValid = await verifyWebhook(request, env.WEBHOOK_SECRET);
+ if (!isValid) {
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ // Parse event
+ const event = await request.json();
+
+ // Queue processing (don't block response)
+ env.ctx.waitUntil(processWebhook(event, env));
+
+ // Return 200 immediately
+ return new Response('OK', { status: 200 });
+ },
+};
+
+async function processWebhook(event: any, env: Env) {
+ // Handle event logic here
+ // Runs after response is sent
+}
+```
+
+---
+
+### 2. Implement Idempotency
+
+Track processed events to avoid duplicates:
+
+```typescript
+async function processWebhook(event: any, env: Env) {
+ const eventId = event.id || event.event_id || event.sg_event_id;
+
+ // Check if already processed
+ const existing = await env.DB.prepare(`
+ SELECT id FROM processed_events WHERE event_id = ?
+ `).bind(eventId).first();
+
+ if (existing) {
+ console.log(`Event already processed: ${eventId}`);
+ return;
+ }
+
+ // Process event
+ await handleEvent(event, env);
+
+ // Mark as processed
+ await env.DB.prepare(`
+ INSERT INTO processed_events (event_id, processed_at)
+ VALUES (?, ?)
+ `).bind(eventId, Date.now()).run();
+}
+```
+
+---
+
+### 3. Handle Retries Gracefully
+
+Providers retry failed webhooks:
+
+- **Resend**: Exponential backoff, up to 3 days
+- **SendGrid**: Up to 3 retries over 10 hours
+- **Mailgun**: Exponential backoff, up to 8 hours
+- **SMTP2Go**: Up to 5 retries over 24 hours
+
+Ensure your handler is idempotent (see above).
+
+---
+
+### 4. Monitor Webhook Health
+
+Track webhook processing metrics:
+
+```typescript
+await env.DB.prepare(`
+ INSERT INTO webhook_metrics (provider, event_type, success, duration_ms)
+ VALUES (?, ?, ?, ?)
+`).bind(provider, event.type, success, duration).run();
+```
+
+Alert on:
+- High failure rates
+- Signature verification failures
+- Slow processing times
+
+---
+
+## Summary
+
+- **Verify signatures** for all webhooks
+- **Return 200 quickly** (use waitUntil for processing)
+- **Implement idempotency** to handle retries
+- **Track metrics** for health monitoring
+- **Handle spam complaints** immediately
+- **Mark permanent bounces** as invalid
diff --git a/skills/email-gateway/scripts/test-provider.sh b/skills/email-gateway/scripts/test-provider.sh
new file mode 100755
index 00000000..e4be1dcc
--- /dev/null
+++ b/skills/email-gateway/scripts/test-provider.sh
@@ -0,0 +1,218 @@
+#!/bin/bash
+#
+# Test Email Provider Connectivity
+#
+# Usage:
+# ./test-provider.sh resend
+# ./test-provider.sh sendgrid
+# ./test-provider.sh mailgun
+# ./test-provider.sh smtp2go
+# ./test-provider.sh all
+#
+
+set -e
+
+PROVIDER="${1:-all}"
+TEST_FROM="${TEST_FROM:[email protected]}"
+TEST_TO="${TEST_TO:[email protected]}"
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+echo "========================================"
+echo "Email Provider Connectivity Test"
+echo "========================================"
+echo ""
+
+# Test Resend
+test_resend() {
+ echo -n "Testing Resend... "
+
+ if [ -z "$RESEND_API_KEY" ]; then
+ echo -e "${RED}FAILED${NC} - RESEND_API_KEY not set"
+ return 1
+ fi
+
+ RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://api.resend.com/emails \
+ -H "Authorization: Bearer $RESEND_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"from\": \"$TEST_FROM\",
+ \"to\": \"$TEST_TO\",
+ \"subject\": \"Test Email from Resend\",
+ \"html\": \"<p>This is a test email.</p>\"
+ }")
+
+ HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
+ BODY=$(echo "$RESPONSE" | sed '$d')
+
+ if [ "$HTTP_CODE" -eq 200 ]; then
+ EMAIL_ID=$(echo "$BODY" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
+ echo -e "${GREEN}SUCCESS${NC} - Email ID: $EMAIL_ID"
+ return 0
+ else
+ echo -e "${RED}FAILED${NC} - HTTP $HTTP_CODE"
+ echo "$BODY"
+ return 1
+ fi
+}
+
+# Test SendGrid
+test_sendgrid() {
+ echo -n "Testing SendGrid... "
+
+ if [ -z "$SENDGRID_API_KEY" ]; then
+ echo -e "${RED}FAILED${NC} - SENDGRID_API_KEY not set"
+ return 1
+ fi
+
+ RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://api.sendgrid.com/v3/mail/send \
+ -H "Authorization: Bearer $SENDGRID_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"personalizations\": [{
+ \"to\": [{\"email\": \"$TEST_TO\"}]
+ }],
+ \"from\": {\"email\": \"$TEST_FROM\"},
+ \"subject\": \"Test Email from SendGrid\",
+ \"content\": [{
+ \"type\": \"text/html\",
+ \"value\": \"<p>This is a test email.</p>\"
+ }]
+ }")
+
+ HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
+ BODY=$(echo "$RESPONSE" | sed '$d')
+
+ if [ "$HTTP_CODE" -eq 202 ]; then
+ echo -e "${GREEN}SUCCESS${NC} - Email accepted (HTTP 202)"
+ return 0
+ else
+ echo -e "${RED}FAILED${NC} - HTTP $HTTP_CODE"
+ echo "$BODY"
+ return 1
+ fi
+}
+
+# Test Mailgun
+test_mailgun() {
+ echo -n "Testing Mailgun... "
+
+ if [ -z "$MAILGUN_API_KEY" ] || [ -z "$MAILGUN_DOMAIN" ]; then
+ echo -e "${RED}FAILED${NC} - MAILGUN_API_KEY or MAILGUN_DOMAIN not set"
+ return 1
+ fi
+
+ REGION="${MAILGUN_REGION:-us}"
+ if [ "$REGION" = "eu" ]; then
+ API_URL="https://api.eu.mailgun.net/v3"
+ else
+ API_URL="https://api.mailgun.net/v3"
+ fi
+
+ RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/$MAILGUN_DOMAIN/messages" \
+ -u "api:$MAILGUN_API_KEY" \
+ -F from="$TEST_FROM" \
+ -F to="$TEST_TO" \
+ -F subject="Test Email from Mailgun" \
+ -F html="<p>This is a test email.</p>")
+
+ HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
+ BODY=$(echo "$RESPONSE" | sed '$d')
+
+ if [ "$HTTP_CODE" -eq 200 ]; then
+ MESSAGE_ID=$(echo "$BODY" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
+ echo -e "${GREEN}SUCCESS${NC} - Message ID: $MESSAGE_ID"
+ return 0
+ else
+ echo -e "${RED}FAILED${NC} - HTTP $HTTP_CODE"
+ echo "$BODY"
+ return 1
+ fi
+}
+
+# Test SMTP2Go
+test_smtp2go() {
+ echo -n "Testing SMTP2Go... "
+
+ if [ -z "$SMTP2GO_API_KEY" ]; then
+ echo -e "${RED}FAILED${NC} - SMTP2GO_API_KEY not set"
+ return 1
+ fi
+
+ RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://api.smtp2go.com/v3/email/send \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"api_key\": \"$SMTP2GO_API_KEY\",
+ \"to\": [\"<$TEST_TO>\"],
+ \"sender\": \"$TEST_FROM\",
+ \"subject\": \"Test Email from SMTP2Go\",
+ \"html_body\": \"<p>This is a test email.</p>\"
+ }")
+
+ HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
+ BODY=$(echo "$RESPONSE" | sed '$d')
+
+ if [ "$HTTP_CODE" -eq 200 ]; then
+ SUCCEEDED=$(echo "$BODY" | grep -o '"succeeded":[0-9]*' | cut -d':' -f2)
+ FAILED=$(echo "$BODY" | grep -o '"failed":[0-9]*' | cut -d':' -f2)
+
+ if [ "$SUCCEEDED" -eq 1 ]; then
+ EMAIL_ID=$(echo "$BODY" | grep -o '"email_id":"[^"]*"' | cut -d'"' -f4)
+ echo -e "${GREEN}SUCCESS${NC} - Email ID: $EMAIL_ID"
+ return 0
+ else
+ echo -e "${RED}FAILED${NC} - $FAILED recipients failed"
+ echo "$BODY"
+ return 1
+ fi
+ else
+ echo -e "${RED}FAILED${NC} - HTTP $HTTP_CODE"
+ echo "$BODY"
+ return 1
+ fi
+}
+
+# Run tests
+if [ "$PROVIDER" = "all" ]; then
+ echo "Testing all providers..."
+ echo ""
+
+ PASSED=0
+ FAILED=0
+
+ test_resend && PASSED=$((PASSED+1)) || FAILED=$((FAILED+1))
+ test_sendgrid && PASSED=$((PASSED+1)) || FAILED=$((FAILED+1))
+ test_mailgun && PASSED=$((PASSED+1)) || FAILED=$((FAILED+1))
+ test_smtp2go && PASSED=$((PASSED+1)) || FAILED=$((FAILED+1))
+
+ echo ""
+ echo "========================================"
+ echo "Results: ${GREEN}$PASSED passed${NC}, ${RED}$FAILED failed${NC}"
+ echo "========================================"
+
+ [ $FAILED -eq 0 ] && exit 0 || exit 1
+else
+ case "$PROVIDER" in
+ resend)
+ test_resend
+ ;;
+ sendgrid)
+ test_sendgrid
+ ;;
+ mailgun)
+ test_mailgun
+ ;;
+ smtp2go)
+ test_smtp2go
+ ;;
+ *)
+ echo "Unknown provider: $PROVIDER"
+ echo "Usage: $0 {resend|sendgrid|mailgun|smtp2go|all}"
+ exit 1
+ ;;
+ esac
+fi
diff --git a/skills/email-gateway/templates/mailgun-send.ts b/skills/email-gateway/templates/mailgun-send.ts
new file mode 100644
index 00000000..2482b564
--- /dev/null
+++ b/skills/email-gateway/templates/mailgun-send.ts
@@ -0,0 +1,317 @@
+/**
+ * Mailgun Email Sending Template
+ *
+ * Send emails via Mailgun API with FormData.
+ * Requires MAILGUN_API_KEY and MAILGUN_DOMAIN environment variables.
+ */
+
+interface Env {
+ MAILGUN_API_KEY: string;
+ MAILGUN_DOMAIN: string;
+ MAILGUN_REGION?: 'us' | 'eu'; // Default: us
+}
+
+interface MailgunResponse {
+ id: string;
+ message: string;
+}
+
+interface MailgunError {
+ message: string;
+}
+
+/**
+ * Get Mailgun API base URL based on region
+ */
+function getMailgunApiUrl(region: 'us' | 'eu' = 'us'): string {
+ return region === 'eu'
+ ? 'https://api.eu.mailgun.net/v3'
+ : 'https://api.mailgun.net/v3';
+}
+
+/**
+ * Send email via Mailgun API
+ */
+export async function sendEmail(
+ from: string,
+ to: string | string[],
+ subject: string,
+ html: string,
+ options: {
+ text?: string;
+ cc?: string | string[];
+ bcc?: string | string[];
+ replyTo?: string;
+ tags?: string[];
+ tracking?: boolean;
+ trackingClicks?: boolean | 'htmlonly';
+ trackingOpens?: boolean;
+ customVariables?: Record<string, string>;
+ } = {},
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const formData = new FormData();
+
+ formData.append('from', from);
+
+ if (Array.isArray(to)) {
+ to.forEach(recipient => formData.append('to', recipient));
+ } else {
+ formData.append('to', to);
+ }
+
+ formData.append('subject', subject);
+ formData.append('html', html);
+
+ if (options.text) {
+ formData.append('text', options.text);
+ }
+
+ if (options.cc) {
+ const ccList = Array.isArray(options.cc) ? options.cc : [options.cc];
+ ccList.forEach(recipient => formData.append('cc', recipient));
+ }
+
+ if (options.bcc) {
+ const bccList = Array.isArray(options.bcc) ? options.bcc : [options.bcc];
+ bccList.forEach(recipient => formData.append('bcc', recipient));
+ }
+
+ if (options.replyTo) {
+ formData.append('h:Reply-To', options.replyTo);
+ }
+
+ if (options.tags) {
+ options.tags.forEach(tag => formData.append('o:tag', tag));
+ }
+
+ if (options.tracking !== undefined) {
+ formData.append('o:tracking', options.tracking ? 'yes' : 'no');
+ }
+
+ if (options.trackingClicks !== undefined) {
+ formData.append(
+ 'o:tracking-clicks',
+ typeof options.trackingClicks === 'boolean'
+ ? (options.trackingClicks ? 'yes' : 'no')
+ : options.trackingClicks
+ );
+ }
+
+ if (options.trackingOpens !== undefined) {
+ formData.append('o:tracking-opens', options.trackingOpens ? 'yes' : 'no');
+ }
+
+ if (options.customVariables) {
+ formData.append('h:X-Mailgun-Variables', JSON.stringify(options.customVariables));
+ }
+
+ const apiUrl = getMailgunApiUrl(env.MAILGUN_REGION);
+ const response = await fetch(`${apiUrl}/${env.MAILGUN_DOMAIN}/messages`, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ const error: MailgunError = await response.json();
+ return {
+ success: false,
+ error: error.message,
+ };
+ }
+
+ const data: MailgunResponse = await response.json();
+ return {
+ success: true,
+ id: data.id,
+ };
+}
+
+/**
+ * Send email with attachment
+ */
+export async function sendEmailWithAttachment(
+ from: string,
+ to: string,
+ subject: string,
+ html: string,
+ attachment: File,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const formData = new FormData();
+
+ formData.append('from', from);
+ formData.append('to', to);
+ formData.append('subject', subject);
+ formData.append('html', html);
+ formData.append('attachment', attachment);
+
+ const apiUrl = getMailgunApiUrl(env.MAILGUN_REGION);
+ const response = await fetch(`${apiUrl}/${env.MAILGUN_DOMAIN}/messages`, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ const error: MailgunError = await response.json();
+ return {
+ success: false,
+ error: error.message,
+ };
+ }
+
+ const data: MailgunResponse = await response.json();
+ return {
+ success: true,
+ id: data.id,
+ };
+}
+
+/**
+ * Send email using Mailgun template
+ */
+export async function sendTemplateEmail(
+ from: string,
+ to: string,
+ subject: string,
+ templateName: string,
+ templateVariables: Record<string, unknown>,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const formData = new FormData();
+
+ formData.append('from', from);
+ formData.append('to', to);
+ formData.append('subject', subject);
+ formData.append('template', templateName);
+ formData.append('h:X-Mailgun-Variables', JSON.stringify(templateVariables));
+
+ const apiUrl = getMailgunApiUrl(env.MAILGUN_REGION);
+ const response = await fetch(`${apiUrl}/${env.MAILGUN_DOMAIN}/messages`, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ const error: MailgunError = await response.json();
+ return {
+ success: false,
+ error: error.message,
+ };
+ }
+
+ const data: MailgunResponse = await response.json();
+ return {
+ success: true,
+ id: data.id,
+ };
+}
+
+/**
+ * Send password reset email
+ */
+export async function sendPasswordReset(
+ to: string,
+ resetToken: string,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;
+
+ const html = `
+ <!DOCTYPE html>
+ <html>
+ <body style="font-family: Arial, sans-serif;">
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
+ <h1>Reset Your Password</h1>
+ <p>Click the link below to reset your password:</p>
+ <a href="${resetUrl}"
+ style="display: inline-block; padding: 12px 24px; background: #000; color: #fff; text-decoration: none; border-radius: 4px;">
+ Reset Password
+ </a>
+ <p style="margin-top: 20px; color: #666; font-size: 14px;">
+ This link expires in 1 hour.
+ </p>
+ </div>
+ </body>
+ </html>
+ `;
+
+ return sendEmail(
+ to,
+ 'Reset Your Password',
+ html,
+ {
+ tags: ['password-reset'],
+ tracking: true,
+ },
+ env
+ );
+}
+
+/**
+ * Example Cloudflare Worker
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+
+ if (url.pathname === '/send-reset') {
+ const { email, token } = await request.json();
+ const result = await sendPasswordReset(email, token, env);
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true, id: result.id }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ if (url.pathname === '/send-welcome') {
+ const { email, name } = await request.json();
+
+ const result = await sendEmail(
+ email,
+ `Welcome, ${name}!`,
+ `<h1>Welcome to Our App</h1><p>Hi ${name}, thanks for signing up!</p>`,
+ {
+ tags: ['welcome'],
+ tracking: true,
+ trackingClicks: 'htmlonly',
+ trackingOpens: true,
+ },
+ env
+ );
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true, id: result.id }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response('Not found', { status: 404 });
+ },
+};
diff --git a/skills/email-gateway/templates/mailgun-webhooks.ts b/skills/email-gateway/templates/mailgun-webhooks.ts
new file mode 100644
index 00000000..38f8075c
--- /dev/null
+++ b/skills/email-gateway/templates/mailgun-webhooks.ts
@@ -0,0 +1,292 @@
+/**
+ * Mailgun Webhook Handler
+ *
+ * Handle Mailgun webhook events (delivered, bounced, complained, opened, clicked).
+ * Requires MAILGUN_WEBHOOK_SIGNING_KEY environment variable.
+ */
+
+import { createHmac } from 'crypto';
+
+interface Env {
+ MAILGUN_WEBHOOK_SIGNING_KEY: string;
+ // Optional: Database binding for storing events
+ DB?: D1Database;
+}
+
+interface MailgunWebhook {
+ signature: {
+ timestamp: string;
+ token: string;
+ signature: string;
+ };
+ 'event-data': {
+ event: 'delivered' | 'failed' | 'opened' | 'clicked' | 'unsubscribed' | 'complained';
+ timestamp: number;
+ id: string;
+ recipient: string;
+ message: {
+ headers: {
+ 'message-id': string;
+ from: string;
+ to: string;
+ subject: string;
+ };
+ };
+ tags?: string[];
+ 'user-variables'?: Record<string, string>;
+ 'delivery-status'?: {
+ message: string;
+ code: number;
+ description: string;
+ };
+ severity?: 'temporary' | 'permanent';
+ reason?: 'bounce' | 'suppress-bounce' | 'suppress-unsubscribe' | 'suppress-complaint';
+ url?: string; // For clicked events
+ };
+}
+
+/**
+ * Verify Mailgun webhook signature
+ */
+export function verifyWebhookSignature(
+ timestamp: string,
+ token: string,
+ signature: string,
+ signingKey: string
+): boolean {
+ const encodedToken = createHmac('sha256', signingKey)
+ .update(`${timestamp}${token}`)
+ .digest('hex');
+
+ return encodedToken === signature;
+}
+
+/**
+ * Handle webhook event
+ */
+export async function handleWebhookEvent(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ console.log(`Mailgun event: ${event.event} for ${event.recipient}`);
+
+ switch (event.event) {
+ case 'delivered':
+ await handleDelivered(event, env);
+ break;
+
+ case 'failed':
+ await handleFailed(event, env);
+ break;
+
+ case 'opened':
+ await handleOpened(event, env);
+ break;
+
+ case 'clicked':
+ await handleClicked(event, env);
+ break;
+
+ case 'unsubscribed':
+ await handleUnsubscribed(event, env);
+ break;
+
+ case 'complained':
+ await handleComplained(event, env);
+ break;
+
+ default:
+ console.log(`Unhandled event type: ${event.event}`);
+ }
+}
+
+async function handleDelivered(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ // Track successful delivery
+ if (env.DB) {
+ await env.DB.prepare(`
+ INSERT INTO email_events (event_type, email, message_id, timestamp)
+ VALUES (?, ?, ?, ?)
+ `).bind(
+ 'delivered',
+ event.recipient,
+ event.message.headers['message-id'],
+ event.timestamp
+ ).run();
+ }
+}
+
+async function handleFailed(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ const isPermanent = event.severity === 'permanent';
+
+ console.log(`Email failed: ${event.recipient} (${isPermanent ? 'permanent' : 'temporary'})`);
+
+ if (isPermanent) {
+ // Mark email as invalid in database
+ if (env.DB) {
+ await env.DB.prepare(`
+ UPDATE users SET email_valid = 0 WHERE email = ?
+ `).bind(event.recipient).run();
+ }
+ }
+
+ // Log failure
+ if (env.DB) {
+ await env.DB.prepare(`
+ INSERT INTO email_events (event_type, email, message_id, timestamp, metadata)
+ VALUES (?, ?, ?, ?, ?)
+ `).bind(
+ 'failed',
+ event.recipient,
+ event.message.headers['message-id'],
+ event.timestamp,
+ JSON.stringify({
+ severity: event.severity,
+ reason: event.reason,
+ code: event['delivery-status']?.code,
+ description: event['delivery-status']?.description,
+ })
+ ).run();
+ }
+}
+
+async function handleOpened(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ // Track email open
+ if (env.DB) {
+ await env.DB.prepare(`
+ INSERT INTO email_opens (email, message_id, timestamp)
+ VALUES (?, ?, ?)
+ `).bind(
+ event.recipient,
+ event.message.headers['message-id'],
+ event.timestamp
+ ).run();
+ }
+}
+
+async function handleClicked(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ // Track email click
+ if (env.DB) {
+ await env.DB.prepare(`
+ INSERT INTO email_clicks (email, message_id, url, timestamp)
+ VALUES (?, ?, ?, ?)
+ `).bind(
+ event.recipient,
+ event.message.headers['message-id'],
+ event.url || '',
+ event.timestamp
+ ).run();
+ }
+}
+
+async function handleUnsubscribed(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ console.log(`User unsubscribed: ${event.recipient}`);
+
+ // Update user subscription status
+ if (env.DB) {
+ await env.DB.prepare(`
+ UPDATE users SET subscribed = 0 WHERE email = ?
+ `).bind(event.recipient).run();
+ }
+}
+
+async function handleComplained(
+ event: MailgunWebhook['event-data'],
+ env: Env
+): Promise<void> {
+ console.log(`Spam complaint from: ${event.recipient}`);
+
+ // Immediately unsubscribe and mark as complained
+ if (env.DB) {
+ await env.DB.prepare(`
+ UPDATE users SET subscribed = 0, spam_complained = 1 WHERE email = ?
+ `).bind(event.recipient).run();
+ }
+}
+
+/**
+ * Cloudflare Worker handler
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ if (request.method !== 'POST') {
+ return new Response('Method not allowed', { status: 405 });
+ }
+
+ const body = await request.text();
+ const webhook: MailgunWebhook = JSON.parse(body);
+
+ // Verify signature
+ const isValid = verifyWebhookSignature(
+ webhook.signature.timestamp,
+ webhook.signature.token,
+ webhook.signature.signature,
+ env.MAILGUN_WEBHOOK_SIGNING_KEY
+ );
+
+ if (!isValid) {
+ console.error('Invalid webhook signature');
+ return new Response('Invalid signature', { status: 401 });
+ }
+
+ // Process event
+ try {
+ await handleWebhookEvent(webhook['event-data'], env);
+ return new Response('OK', { status: 200 });
+ } catch (error) {
+ console.error('Error processing webhook:', error);
+ return new Response('Internal error', { status: 500 });
+ }
+ },
+};
+
+/**
+ * D1 Schema for webhook events
+ */
+export const schema = `
+ CREATE TABLE IF NOT EXISTS email_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ event_type TEXT NOT NULL,
+ email TEXT NOT NULL,
+ message_id TEXT NOT NULL,
+ timestamp INTEGER NOT NULL,
+ metadata TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS email_opens (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ email TEXT NOT NULL,
+ message_id TEXT NOT NULL,
+ timestamp INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE IF NOT EXISTS email_clicks (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ email TEXT NOT NULL,
+ message_id TEXT NOT NULL,
+ url TEXT NOT NULL,
+ timestamp INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX idx_email_events_email ON email_events(email);
+ CREATE INDEX idx_email_events_timestamp ON email_events(timestamp);
+ CREATE INDEX idx_email_opens_message_id ON email_opens(message_id);
+ CREATE INDEX idx_email_clicks_message_id ON email_clicks(message_id);
+`;
diff --git a/skills/email-gateway/templates/resend-basic.ts b/skills/email-gateway/templates/resend-basic.ts
new file mode 100644
index 00000000..bbd2da4b
--- /dev/null
+++ b/skills/email-gateway/templates/resend-basic.ts
@@ -0,0 +1,109 @@
+/**
+ * Resend Basic Email Template
+ *
+ * Minimal working example for sending emails via Resend API.
+ * Requires RESEND_API_KEY environment variable.
+ */
+
+interface Env {
+ RESEND_API_KEY: string;
+}
+
+interface ResendEmail {
+ from: string;
+ to: string | string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ cc?: string | string[];
+ bcc?: string | string[];
+ replyTo?: string | string[];
+ headers?: Record<string, string>;
+ attachments?: Array<{
+ filename: string;
+ content: string; // base64
+ }>;
+ tags?: Record<string, string>;
+ scheduledAt?: string; // ISO 8601
+}
+
+interface ResendResponse {
+ id: string;
+}
+
+interface ResendError {
+ statusCode: number;
+ message: string;
+ name: string;
+}
+
+/**
+ * Send email via Resend API
+ */
+export async function sendEmail(
+ email: ResendEmail,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ try {
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(email),
+ });
+
+ if (!response.ok) {
+ const error: ResendError = await response.json();
+ return {
+ success: false,
+ error: `${error.statusCode}: ${error.message}`,
+ };
+ }
+
+ const data: ResendResponse = await response.json();
+ return {
+ success: true,
+ id: data.id,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: (error as Error).message,
+ };
+ }
+}
+
+/**
+ * Example usage
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const result = await sendEmail(
+ {
+ subject: 'Welcome to Our App',
+ html: `
+ <h1>Welcome!</h1>
+ <p>Thanks for signing up.</p>
+ `,
+ text: 'Welcome! Thanks for signing up.',
+ },
+ env
+ );
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ emailId: result.id }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ },
+};
diff --git a/skills/email-gateway/templates/resend-react-email.tsx b/skills/email-gateway/templates/resend-react-email.tsx
new file mode 100644
index 00000000..d6dfb506
--- /dev/null
+++ b/skills/email-gateway/templates/resend-react-email.tsx
@@ -0,0 +1,185 @@
+/**
+ * Resend React Email Template
+ *
+ * Use React components for email design (requires Node.js environment).
+ * Install: npm install resend react-email @react-email/components
+ *
+ * For Cloudflare Workers: Pre-render with @react-email/render
+ */
+
+import { Resend } from 'resend';
+import {
+ Html,
+ Head,
+ Body,
+ Container,
+ Heading,
+ Text,
+ Button,
+ Section,
+ Hr,
+} from '@react-email/components';
+
+// ============================================================================
+// Email Component
+// ============================================================================
+
+interface WelcomeEmailProps {
+ name: string;
+ confirmUrl: string;
+}
+
+export function WelcomeEmail({ name, confirmUrl }: WelcomeEmailProps) {
+ return (
+ <Html>
+ <Head />
+ <Body style={styles.body}>
+ <Container style={styles.container}>
+ <Heading style={styles.heading}>Welcome, {name}!</Heading>
+
+ <Text style={styles.text}>
+ Thanks for signing up. We're excited to have you on board.
+ </Text>
+
+ <Section style={styles.buttonSection}>
+ <Button href={confirmUrl} style={styles.button}>
+ Confirm Your Email
+ </Button>
+ </Section>
+
+ <Hr style={styles.hr} />
+
+ <Text style={styles.footer}>
+ If you didn't create this account, you can safely ignore this email.
+ </Text>
+ </Container>
+ </Body>
+ </Html>
+ );
+}
+
+const styles = {
+ body: {
+ backgroundColor: '#f6f9fc',
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
+ },
+ container: {
+ backgroundColor: '#ffffff',
+ margin: '0 auto',
+ padding: '20px 0 48px',
+ marginBottom: '64px',
+ },
+ heading: {
+ fontSize: '32px',
+ lineHeight: '1.3',
+ fontWeight: '700',
+ color: '#484848',
+ padding: '0 48px',
+ },
+ text: {
+ fontSize: '16px',
+ lineHeight: '1.6',
+ color: '#484848',
+ padding: '24px 48px 0',
+ },
+ buttonSection: {
+ padding: '24px 48px',
+ },
+ button: {
+ backgroundColor: '#000000',
+ borderRadius: '8px',
+ color: '#ffffff',
+ fontSize: '16px',
+ fontWeight: '600',
+ textDecoration: 'none',
+ textAlign: 'center' as const,
+ display: 'block',
+ width: '100%',
+ padding: '12px 0',
+ },
+ hr: {
+ borderColor: '#e6ebf1',
+ margin: '20px 48px',
+ },
+ footer: {
+ fontSize: '14px',
+ lineHeight: '1.5',
+ color: '#8898aa',
+ padding: '0 48px',
+ },
+};
+
+// ============================================================================
+// Node.js Usage (with Resend SDK)
+// ============================================================================
+
+const resend = new Resend(process.env.RESEND_API_KEY);
+
+export async function sendWelcomeEmail(name: string, email: string, confirmUrl: string) {
+ try {
+ const data = await resend.emails.send({
+ to: email,
+ subject: `Welcome, ${name}!`,
+ react: WelcomeEmail({ name, confirmUrl }),
+ });
+
+ return { success: true, id: data.id };
+ } catch (error) {
+ return { success: false, error: (error as Error).message };
+ }
+}
+
+// ============================================================================
+// Cloudflare Workers Usage (pre-render)
+// ============================================================================
+
+import { render } from '@react-email/render';
+
+interface Env {
+ RESEND_API_KEY: string;
+}
+
+export async function sendWelcomeEmailWorker(
+ name: string,
+ email: string,
+ confirmUrl: string,
+ env: Env
+) {
+ // Render React component to HTML string
+ const html = render(WelcomeEmail({ name, confirmUrl }));
+
+ const response = await fetch('https://api.resend.com/emails', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.RESEND_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ to: email,
+ subject: `Welcome, ${name}!`,
+ html,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ return { success: false, error: error.message };
+ }
+
+ const data = await response.json();
+ return { success: true, id: data.id };
+}
+
+// ============================================================================
+// Preview Email (Development)
+// ============================================================================
+
+// Create emails/preview.tsx for local development:
+// import { WelcomeEmail } from './welcome';
+// export default function Preview() {
+// return <WelcomeEmail name="Alice" confirmUrl="https://example.com/confirm" />;
+// }
+//
+// Run: npm run email dev
diff --git a/skills/email-gateway/templates/sendgrid-dynamic-template.ts b/skills/email-gateway/templates/sendgrid-dynamic-template.ts
new file mode 100644
index 00000000..18a8eb2a
--- /dev/null
+++ b/skills/email-gateway/templates/sendgrid-dynamic-template.ts
@@ -0,0 +1,213 @@
+/**
+ * SendGrid Dynamic Template
+ *
+ * Use SendGrid's dynamic templates with handlebars variables.
+ * Create templates in SendGrid dashboard first.
+ */
+
+interface Env {
+ SENDGRID_API_KEY: string;
+}
+
+interface DynamicTemplateData {
+ [key: string]: unknown;
+}
+
+/**
+ * Send email using dynamic template
+ */
+export async function sendDynamicTemplate(
+ to: string | Array<{ email: string; name?: string }>,
+ templateId: string,
+ dynamicData: DynamicTemplateData,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const recipients = Array.isArray(to)
+ ? to
+ : [{ email: to }];
+
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: [{
+ to: recipients,
+ dynamic_template_data: dynamicData,
+ }],
+ from: { email: '[email protected]', name: 'Your App' },
+ template_id: templateId,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ return {
+ success: false,
+ error: error.errors?.map((e: any) => e.message).join(', ') || 'Unknown error',
+ };
+ }
+
+ return { success: true };
+}
+
+/**
+ * Send batch emails with different data per recipient
+ */
+export async function sendBatchDynamicTemplate(
+ recipients: Array<{
+ email: string;
+ name?: string;
+ data: DynamicTemplateData;
+ }>,
+ templateId: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ personalizations: recipients.map(r => ({
+ to: [{ email: r.email, name: r.name }],
+ dynamic_template_data: r.data,
+ })),
+ from: { email: '[email protected]', name: 'Your App' },
+ template_id: templateId,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ return {
+ success: false,
+ error: error.errors?.map((e: any) => e.message).join(', ') || 'Unknown error',
+ };
+ }
+
+ return { success: true };
+}
+
+/**
+ * Example: Welcome email template
+ *
+ * Create template in SendGrid dashboard:
+ * - Subject: Welcome to {{companyName}}, {{firstName}}!
+ * - Body:
+ * <h1>Hi {{firstName}},</h1>
+ * <p>Welcome to {{companyName}}! We're excited to have you.</p>
+ * <a href="{{confirmUrl}}">Confirm Your Email</a>
+ */
+export async function sendWelcomeEmail(
+ email: string,
+ firstName: string,
+ confirmUrl: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const WELCOME_TEMPLATE_ID = 'd-xxxxxxxxxxxxxxxxxxxxxxxx';
+
+ return sendDynamicTemplate(
+ email,
+ WELCOME_TEMPLATE_ID,
+ {
+ firstName,
+ companyName: 'Your App',
+ confirmUrl,
+ },
+ env
+ );
+}
+
+/**
+ * Example: Weekly digest template
+ *
+ * Template variables:
+ * - {{userName}}
+ * - {{weekStart}}
+ * - {{weekEnd}}
+ * - {{activities}} (array)
+ */
+export async function sendWeeklyDigest(
+ email: string,
+ userName: string,
+ activities: Array<{ title: string; date: string; url: string }>,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const DIGEST_TEMPLATE_ID = 'd-yyyyyyyyyyyyyyyyyyyyyyyy';
+
+ const now = new Date();
+ const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
+
+ return sendDynamicTemplate(
+ email,
+ DIGEST_TEMPLATE_ID,
+ {
+ userName,
+ weekStart: weekStart.toLocaleDateString(),
+ weekEnd: now.toLocaleDateString(),
+ activities,
+ },
+ env
+ );
+}
+
+/**
+ * Example: Batch onboarding emails
+ */
+export async function sendBatchOnboarding(
+ users: Array<{
+ email: string;
+ name: string;
+ plan: string;
+ trialEnds: string;
+ }>,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const ONBOARDING_TEMPLATE_ID = 'd-zzzzzzzzzzzzzzzzzzzzzzzz';
+
+ return sendBatchDynamicTemplate(
+ users.map(user => ({
+ email: user.email,
+ name: user.name,
+ data: {
+ firstName: user.name.split(' ')[0],
+ plan: user.plan,
+ trialEnds: user.trialEnds,
+ },
+ })),
+ ONBOARDING_TEMPLATE_ID,
+ env
+ );
+}
+
+/**
+ * Example Cloudflare Worker
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+
+ if (url.pathname === '/send-welcome') {
+ const { email, firstName, confirmUrl } = await request.json();
+ const result = await sendWelcomeEmail(email, firstName, confirmUrl, env);
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response('Not found', { status: 404 });
+ },
+};
diff --git a/skills/email-gateway/templates/sendgrid-transactional.ts b/skills/email-gateway/templates/sendgrid-transactional.ts
new file mode 100644
index 00000000..ca214978
--- /dev/null
+++ b/skills/email-gateway/templates/sendgrid-transactional.ts
@@ -0,0 +1,225 @@
+/**
+ * SendGrid Transactional Email Template
+ *
+ * Send individual transactional emails via SendGrid Mail Send API.
+ * Requires SENDGRID_API_KEY environment variable.
+ */
+
+interface Env {
+ SENDGRID_API_KEY: string;
+}
+
+interface SendGridEmail {
+ personalizations: Array<{
+ to: Array<{ email: string; name?: string }>;
+ cc?: Array<{ email: string; name?: string }>;
+ bcc?: Array<{ email: string; name?: string }>;
+ subject?: string;
+ headers?: Record<string, string>;
+ substitutions?: Record<string, string>;
+ custom_args?: Record<string, string>;
+ }>;
+ from: { email: string; name?: string };
+ reply_to?: { email: string; name?: string };
+ subject?: string;
+ content?: Array<{
+ type: 'text/plain' | 'text/html';
+ value: string;
+ }>;
+ attachments?: Array<{
+ content: string; // base64
+ filename: string;
+ type?: string;
+ disposition?: 'inline' | 'attachment';
+ content_id?: string;
+ }>;
+ categories?: string[];
+ send_at?: number; // Unix timestamp
+ custom_args?: Record<string, string>;
+ asm?: {
+ group_id: number;
+ groups_to_display?: number[];
+ };
+}
+
+interface SendGridError {
+ errors: Array<{
+ message: string;
+ field?: string;
+ help?: string;
+ }>;
+}
+
+/**
+ * Send email via SendGrid API
+ */
+export async function sendEmail(
+ email: SendGridEmail,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(email),
+ });
+
+ if (!response.ok) {
+ const error: SendGridError = await response.json();
+ const errorMessages = error.errors.map(e => e.message).join(', ');
+ return {
+ success: false,
+ error: `SendGrid Error: ${errorMessages}`,
+ };
+ }
+
+ // SendGrid returns 202 with no body on success
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: (error as Error).message,
+ };
+ }
+}
+
+/**
+ * Send simple email helper
+ */
+export async function sendSimpleEmail(
+ to: string,
+ subject: string,
+ html: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ return sendEmail(
+ {
+ personalizations: [{
+ to: [{ email: to }],
+ }],
+ from: { email: '[email protected]', name: 'Your App' },
+ subject,
+ content: [{
+ type: 'text/html',
+ value: html,
+ }],
+ },
+ env
+ );
+}
+
+/**
+ * Send password reset email
+ */
+export async function sendPasswordReset(
+ to: string,
+ resetToken: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;
+
+ const html = `
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ </head>
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
+ <h1 style="color: #000;">Reset Your Password</h1>
+ <p>You requested to reset your password. Click the button below to continue:</p>
+ <div style="margin: 30px 0;">
+ <a href="${resetUrl}"
+ style="display: inline-block; padding: 12px 24px; background: #000; color: #fff; text-decoration: none; border-radius: 4px;">
+ Reset Password
+ </a>
+ </div>
+ <p style="color: #666; font-size: 14px;">
+ This link expires in 1 hour. If you didn't request this, you can safely ignore this email.
+ </p>
+ </div>
+ </body>
+ </html>
+ `;
+
+ return sendEmail(
+ {
+ personalizations: [{
+ to: [{ email: to }],
+ }],
+ from: { email: '[email protected]', name: 'Your App' },
+ subject: 'Reset Your Password',
+ content: [{
+ type: 'text/html',
+ value: html,
+ }],
+ categories: ['password-reset'],
+ },
+ env
+ );
+}
+
+/**
+ * Send email with attachment
+ */
+export async function sendEmailWithAttachment(
+ to: string,
+ subject: string,
+ html: string,
+ attachmentContent: string, // base64
+ attachmentFilename: string,
+ env: Env
+): Promise<{ success: boolean; error?: string }> {
+ return sendEmail(
+ {
+ personalizations: [{
+ to: [{ email: to }],
+ }],
+ from: { email: '[email protected]' },
+ subject,
+ content: [{
+ type: 'text/html',
+ value: html,
+ }],
+ attachments: [{
+ content: attachmentContent,
+ filename: attachmentFilename,
+ type: 'application/pdf',
+ disposition: 'attachment',
+ }],
+ },
+ env
+ );
+}
+
+/**
+ * Example Cloudflare Worker
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+
+ if (url.pathname === '/send-reset') {
+ const { email, token } = await request.json();
+ const result = await sendPasswordReset(email, token, env);
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response('Not found', { status: 404 });
+ },
+};
diff --git a/skills/email-gateway/templates/smtp2go-bulk.ts b/skills/email-gateway/templates/smtp2go-bulk.ts
new file mode 100644
index 00000000..d23eef74
--- /dev/null
+++ b/skills/email-gateway/templates/smtp2go-bulk.ts
@@ -0,0 +1,337 @@
+/**
+ * SMTP2Go Bulk Email Template
+ *
+ * Advanced bulk sending with rate limiting, retry logic, and progress tracking.
+ * Optimized for large email campaigns via SMTP2Go API.
+ */
+
+interface Env {
+ SMTP2GO_API_KEY: string;
+ // Optional: KV for rate limiting
+ RATE_LIMITS?: KVNamespace;
+ // Optional: D1 for tracking sends
+ DB?: D1Database;
+}
+
+interface BulkEmailRecipient {
+ email: string;
+ subject: string;
+ html: string;
+ text?: string;
+ customHeaders?: Record<string, string>;
+}
+
+interface BulkSendResult {
+ total: number;
+ succeeded: number;
+ failed: number;
+ results: Array<{
+ email: string;
+ success: boolean;
+ id?: string;
+ error?: string;
+ }>;
+}
+
+/**
+ * Format email address for SMTP2Go (requires angle brackets)
+ */
+function formatEmail(email: string): string {
+ return email.includes('<') ? email : `<${email}>`;
+}
+
+/**
+ * Send single email with retry logic
+ */
+async function sendEmailWithRetry(
+ recipient: BulkEmailRecipient,
+ env: Env,
+ maxRetries = 3
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ let lastError: string | undefined;
+
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ try {
+ const response = await fetch('https://api.smtp2go.com/v3/email/send', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ api_key: env.SMTP2GO_API_KEY,
+ to: [formatEmail(recipient.email)],
+ sender: '[email protected]',
+ subject: recipient.subject,
+ html_body: recipient.html,
+ text_body: recipient.text,
+ custom_headers: recipient.customHeaders
+ ? Object.entries(recipient.customHeaders).map(([header, value]) => ({
+ header,
+ value,
+ }))
+ : undefined,
+ }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ lastError = error.data?.error || 'Unknown error';
+
+ // Don't retry 4xx errors (client errors)
+ if (response.status >= 400 && response.status < 500) {
+ return { success: false, error: lastError };
+ }
+
+ // Retry 5xx errors with exponential backoff
+ if (attempt < maxRetries - 1) {
+ await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
+ continue;
+ }
+
+ return { success: false, error: lastError };
+ }
+
+ const data = await response.json();
+
+ if (data.data.failed > 0) {
+ return {
+ success: false,
+ error: data.data.failures?.join(', ') || 'Unknown error',
+ };
+ }
+
+ return {
+ success: true,
+ id: data.data.email_id,
+ };
+ } catch (error) {
+ lastError = (error as Error).message;
+
+ if (attempt < maxRetries - 1) {
+ await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
+ }
+ }
+ }
+
+ return { success: false, error: lastError };
+}
+
+/**
+ * Check rate limit (10 requests/second for SMTP2Go)
+ */
+async function checkRateLimit(env: Env): Promise<boolean> {
+ if (!env.RATE_LIMITS) return true;
+
+ const key = 'smtp2go:rate-limit';
+ const count = await env.RATE_LIMITS.get(key);
+
+ if (!count) {
+ await env.RATE_LIMITS.put(key, '1', { expirationTtl: 1 });
+ return true;
+ }
+
+ const currentCount = parseInt(count);
+ if (currentCount >= 10) {
+ return false;
+ }
+
+ await env.RATE_LIMITS.put(key, String(currentCount + 1), { expirationTtl: 1 });
+ return true;
+}
+
+/**
+ * Send bulk emails with rate limiting
+ */
+export async function sendBulkEmails(
+ recipients: BulkEmailRecipient[],
+ env: Env,
+ options: {
+ batchSize?: number;
+ delayBetweenBatches?: number;
+ onProgress?: (sent: number, total: number) => void;
+ } = {}
+): Promise<BulkSendResult> {
+ const batchSize = options.batchSize || 100;
+ const delayBetweenBatches = options.delayBetweenBatches || 10000; // 10 seconds
+
+ const results: BulkSendResult['results'] = [];
+ let succeeded = 0;
+ let failed = 0;
+
+ // Process in batches
+ for (let i = 0; i < recipients.length; i += batchSize) {
+ const batch = recipients.slice(i, i + batchSize);
+
+ // Send batch with rate limiting
+ for (const recipient of batch) {
+ // Wait if rate limit reached
+ let canSend = await checkRateLimit(env);
+ while (!canSend) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ canSend = await checkRateLimit(env);
+ }
+
+ const result = await sendEmailWithRetry(recipient, env);
+
+ results.push({
+ email: recipient.email,
+ ...result,
+ });
+
+ if (result.success) {
+ succeeded++;
+ } else {
+ failed++;
+ }
+
+ // Track in database if available
+ if (env.DB) {
+ await env.DB.prepare(`
+ INSERT INTO bulk_send_log (email, success, email_id, error, sent_at)
+ VALUES (?, ?, ?, ?, ?)
+ `).bind(
+ recipient.email,
+ result.success ? 1 : 0,
+ result.id || null,
+ result.error || null,
+ Date.now()
+ ).run();
+ }
+
+ // Progress callback
+ if (options.onProgress) {
+ options.onProgress(i + batch.indexOf(recipient) + 1, recipients.length);
+ }
+
+ // Small delay to avoid overwhelming the API
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+
+ // Delay between batches (except for last batch)
+ if (i + batchSize < recipients.length) {
+ await new Promise(resolve => setTimeout(resolve, delayBetweenBatches));
+ }
+ }
+
+ return {
+ total: recipients.length,
+ succeeded,
+ failed,
+ results,
+ };
+}
+
+/**
+ * Send campaign email to list
+ */
+export async function sendCampaign(
+ recipientEmails: string[],
+ subject: string,
+ html: string,
+ text: string,
+ env: Env
+): Promise<BulkSendResult> {
+ const recipients: BulkEmailRecipient[] = recipientEmails.map(email => ({
+ email,
+ subject,
+ html,
+ text,
+ }));
+
+ return sendBulkEmails(recipients, env, {
+ batchSize: 100,
+ delayBetweenBatches: 10000,
+ onProgress: (sent, total) => {
+ console.log(`Sent ${sent}/${total} emails`);
+ },
+ });
+}
+
+/**
+ * Send personalized bulk emails
+ */
+export async function sendPersonalizedBulk(
+ recipients: Array<{
+ email: string;
+ variables: Record<string, string>;
+ }>,
+ subjectTemplate: string,
+ htmlTemplate: string,
+ textTemplate: string,
+ env: Env
+): Promise<BulkSendResult> {
+ const emails: BulkEmailRecipient[] = recipients.map(recipient => ({
+ email: recipient.email,
+ subject: replaceVariables(subjectTemplate, recipient.variables),
+ html: replaceVariables(htmlTemplate, recipient.variables),
+ text: replaceVariables(textTemplate, recipient.variables),
+ }));
+
+ return sendBulkEmails(emails, env);
+}
+
+/**
+ * Replace {{variable}} placeholders in template
+ */
+function replaceVariables(template: string, variables: Record<string, string>): string {
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
+ return variables[key] || match;
+ });
+}
+
+/**
+ * Cloudflare Worker handler
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+
+ if (url.pathname === '/send-campaign') {
+ const { recipients, subject, html, text } = await request.json();
+
+ const result = await sendCampaign(recipients, subject, html, text, env);
+
+ return new Response(JSON.stringify(result), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ if (url.pathname === '/send-personalized') {
+ const { recipients, subjectTemplate, htmlTemplate, textTemplate } = await request.json();
+
+ const result = await sendPersonalizedBulk(
+ recipients,
+ subjectTemplate,
+ htmlTemplate,
+ textTemplate,
+ env
+ );
+
+ return new Response(JSON.stringify(result), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response('Not found', { status: 404 });
+ },
+};
+
+/**
+ * D1 Schema for bulk send tracking
+ */
+export const schema = `
+ CREATE TABLE IF NOT EXISTS bulk_send_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ email TEXT NOT NULL,
+ success INTEGER NOT NULL,
+ email_id TEXT,
+ error TEXT,
+ sent_at INTEGER NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX idx_bulk_send_email ON bulk_send_log(email);
+ CREATE INDEX idx_bulk_send_sent_at ON bulk_send_log(sent_at);
+`;
diff --git a/skills/email-gateway/templates/smtp2go-send.ts b/skills/email-gateway/templates/smtp2go-send.ts
new file mode 100644
index 00000000..cc916732
--- /dev/null
+++ b/skills/email-gateway/templates/smtp2go-send.ts
@@ -0,0 +1,361 @@
+/**
+ * SMTP2Go Email Sending Template
+ *
+ * Send emails via SMTP2Go API (Australian-based provider).
+ * Requires SMTP2GO_API_KEY environment variable.
+ */
+
+interface Env {
+ SMTP2GO_API_KEY: string;
+}
+
+interface SMTP2GoEmail {
+ api_key: string;
+ to: string[]; // Must use angle brackets: ['<[email protected]>']
+ sender: string;
+ subject: string;
+ html_body?: string;
+ text_body?: string;
+ custom_headers?: Array<{
+ header: string;
+ value: string;
+ }>;
+ attachments?: Array<{
+ filename: string;
+ fileblob: string; // base64
+ mimetype?: string;
+ }>;
+}
+
+interface SMTP2GoResponse {
+ data: {
+ succeeded: number;
+ failed: number;
+ failures?: string[];
+ email_id?: string;
+ };
+}
+
+interface SMTP2GoError {
+ data: {
+ error: string;
+ error_code: string;
+ };
+}
+
+/**
+ * Format email address for SMTP2Go (requires angle brackets)
+ */
+function formatEmail(email: string): string {
+ return email.includes('<') ? email : `<${email}>`;
+}
+
+/**
+ * Send email via SMTP2Go API
+ */
+export async function sendEmail(
+ to: string | string[],
+ subject: string,
+ html: string,
+ options: {
+ text?: string;
+ sender?: string;
+ replyTo?: string;
+ cc?: string[];
+ bcc?: string[];
+ customHeaders?: Record<string, string>;
+ } = {},
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const recipients = Array.isArray(to) ? to : [to];
+
+ const email: SMTP2GoEmail = {
+ api_key: env.SMTP2GO_API_KEY,
+ to: recipients.map(formatEmail),
+ sender: options.sender || '[email protected]',
+ subject,
+ html_body: html,
+ };
+
+ if (options.text) {
+ email.text_body = options.text;
+ }
+
+ if (options.customHeaders) {
+ email.custom_headers = Object.entries(options.customHeaders).map(([header, value]) => ({
+ header,
+ value,
+ }));
+ }
+
+ if (options.replyTo) {
+ email.custom_headers = email.custom_headers || [];
+ email.custom_headers.push({
+ header: 'Reply-To',
+ value: options.replyTo,
+ });
+ }
+
+ if (options.cc) {
+ email.custom_headers = email.custom_headers || [];
+ email.custom_headers.push({
+ header: 'Cc',
+ value: options.cc.map(formatEmail).join(', '),
+ });
+ }
+
+ if (options.bcc) {
+ email.custom_headers = email.custom_headers || [];
+ email.custom_headers.push({
+ header: 'Bcc',
+ value: options.bcc.map(formatEmail).join(', '),
+ });
+ }
+
+ try {
+ const response = await fetch('https://api.smtp2go.com/v3/email/send', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(email),
+ });
+
+ if (!response.ok) {
+ const error: SMTP2GoError = await response.json();
+ return {
+ success: false,
+ error: `${error.data.error_code}: ${error.data.error}`,
+ };
+ }
+
+ const data: SMTP2GoResponse = await response.json();
+
+ if (data.data.failed > 0) {
+ return {
+ success: false,
+ error: data.data.failures?.join(', ') || 'Unknown error',
+ };
+ }
+
+ return {
+ success: true,
+ id: data.data.email_id,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: (error as Error).message,
+ };
+ }
+}
+
+/**
+ * Send email with attachment
+ */
+export async function sendEmailWithAttachment(
+ to: string,
+ subject: string,
+ html: string,
+ attachmentContent: string, // base64
+ attachmentFilename: string,
+ attachmentMimeType: string,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const email: SMTP2GoEmail = {
+ api_key: env.SMTP2GO_API_KEY,
+ to: [formatEmail(to)],
+ sender: '[email protected]',
+ subject,
+ html_body: html,
+ attachments: [{
+ filename: attachmentFilename,
+ fileblob: attachmentContent,
+ mimetype: attachmentMimeType,
+ }],
+ };
+
+ try {
+ const response = await fetch('https://api.smtp2go.com/v3/email/send', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(email),
+ });
+
+ if (!response.ok) {
+ const error: SMTP2GoError = await response.json();
+ return {
+ success: false,
+ error: `${error.data.error_code}: ${error.data.error}`,
+ };
+ }
+
+ const data: SMTP2GoResponse = await response.json();
+
+ if (data.data.failed > 0) {
+ return {
+ success: false,
+ error: data.data.failures?.join(', ') || 'Unknown error',
+ };
+ }
+
+ return {
+ success: true,
+ id: data.data.email_id,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: (error as Error).message,
+ };
+ }
+}
+
+/**
+ * Send password reset email
+ */
+export async function sendPasswordReset(
+ to: string,
+ resetToken: string,
+ env: Env
+): Promise<{ success: boolean; id?: string; error?: string }> {
+ const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;
+
+ const html = `
+ <!DOCTYPE html>
+ <html>
+ <body style="font-family: Arial, sans-serif;">
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
+ <h1>Reset Your Password</h1>
+ <p>Click the link below to reset your password:</p>
+ <a href="${resetUrl}"
+ style="display: inline-block; padding: 12px 24px; background: #000; color: #fff; text-decoration: none; border-radius: 4px;">
+ Reset Password
+ </a>
+ <p style="margin-top: 20px; color: #666; font-size: 14px;">
+ This link expires in 1 hour.
+ </p>
+ </div>
+ </body>
+ </html>
+ `;
+
+ return sendEmail(
+ to,
+ 'Reset Your Password',
+ html,
+ {
+ text: `Reset your password: ${resetUrl}\n\nThis link expires in 1 hour.`,
+ },
+ env
+ );
+}
+
+/**
+ * Send bulk emails (batch processing)
+ */
+export async function sendBulkEmails(
+ recipients: Array<{
+ email: string;
+ subject: string;
+ html: string;
+ }>,
+ env: Env
+): Promise<Array<{ email: string; success: boolean; id?: string; error?: string }>> {
+ const results = [];
+
+ // SMTP2Go allows 100 recipients per request, but we'll send individually
+ // for better error tracking per recipient
+ for (const recipient of recipients) {
+ const result = await sendEmail(
+ recipient.email,
+ recipient.subject,
+ recipient.html,
+ {},
+ env
+ );
+
+ results.push({
+ email: recipient.email,
+ ...result,
+ });
+
+ // Rate limiting: 10 requests/second max
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+
+ return results;
+}
+
+/**
+ * Example Cloudflare Worker
+ */
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+
+ if (url.pathname === '/send-reset') {
+ const { email, token } = await request.json();
+ const result = await sendPasswordReset(email, token, env);
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true, id: result.id }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ if (url.pathname === '/send-welcome') {
+ const { email, name } = await request.json();
+
+ const result = await sendEmail(
+ email,
+ `Welcome, ${name}!`,
+ `<h1>Welcome to Our App</h1><p>Hi ${name}, thanks for signing up!</p>`,
+ {
+ text: `Welcome to Our App\n\nHi ${name}, thanks for signing up!`,
+ },
+ env
+ );
+
+ if (!result.success) {
+ return new Response(JSON.stringify({ error: result.error }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response(JSON.stringify({ success: true, id: result.id }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ if (url.pathname === '/send-bulk') {
+ const { recipients } = await request.json();
+ const results = await sendBulkEmails(recipients, env);
+
+ const succeeded = results.filter(r => r.success).length;
+ const failed = results.filter(r => !r.success).length;
+
+ return new Response(JSON.stringify({
+ succeeded,
+ failed,
+ results,
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ return new Response('Not found', { status: 404 });
+ },
+};