also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,494 +0,0 @@ | ||
| 1 | # Create Mailbox | |
| 2 | ||
| 3 | This guide covers setting up email functionality in your Stacks application, including SMTP configuration, sending emails, and creating custom mailboxes using AWS SES and S3. | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Stacks provides a streamlined email solution leveraging AWS SES for email handling and S3 for storage, offering a serverless email server solution. | |
| 8 | ||
| 9 | ## Benefits | |
| 10 | ||
| 11 | - Unmanaged email server | |
| 12 | - Unlimited email addresses/mailboxes | |
| 13 | - Easily organize messages | |
| 14 | - No server installation or configuration | |
| 15 | - No server maintenance | |
| 16 | ||
| 17 | ## SMTP Configuration | |
| 18 | ||
| 19 | ### Environment Variables | |
| 20 | ||
| 21 | ```env | |
| 22 | # SMTP Configuration | |
| 23 | MAIL_MAILER=ses | |
| 24 | MAIL_FROM_ADDRESS=hello@yourdomain.com | |
| 25 | MAIL_FROM_NAME="Your App Name" | |
| 26 | ||
| 27 | # AWS SES Configuration | |
| 28 | AWS_ACCESS_KEY_ID=your_access_key | |
| 29 | AWS_SECRET_ACCESS_KEY=your_secret_key | |
| 30 | AWS_DEFAULT_REGION=us-east-1 | |
| 31 | ||
| 32 | # Optional: Custom SMTP | |
| 33 | MAIL_HOST=smtp.mailtrap.io | |
| 34 | MAIL_PORT=587 | |
| 35 | MAIL_USERNAME=your_username | |
| 36 | MAIL_PASSWORD=your_password | |
| 37 | MAIL_ENCRYPTION=tls | |
| 38 | ``` | |
| 39 | ||
| 40 | ### Mail Configuration | |
| 41 | ||
| 42 | ```ts | |
| 43 | // config/email.ts | |
| 44 | export default { | |
| 45 | default: 'ses', | |
| 46 | ||
| 47 | mailers: { | |
| 48 | ses: { | |
| 49 | transport: 'ses', | |
| 50 | region: process.env.AWS_DEFAULT_REGION, | |
| 51 | }, | |
| 52 | ||
| 53 | smtp: { | |
| 54 | transport: 'smtp', | |
| 55 | host: process.env.MAIL_HOST, | |
| 56 | port: parseInt(process.env.MAIL_PORT || '587'), | |
| 57 | encryption: process.env.MAIL_ENCRYPTION, | |
| 58 | username: process.env.MAIL_USERNAME, | |
| 59 | password: process.env.MAIL_PASSWORD, | |
| 60 | }, | |
| 61 | ||
| 62 | log: { | |
| 63 | transport: 'log', | |
| 64 | }, | |
| 65 | }, | |
| 66 | ||
| 67 | from: { | |
| 68 | address: process.env.MAIL_FROM_ADDRESS, | |
| 69 | name: process.env.MAIL_FROM_NAME, | |
| 70 | }, | |
| 71 | } | |
| 72 | ``` | |
| 73 | ||
| 74 | ## AWS SES Setup | |
| 75 | ||
| 76 | ### Step 1: Verify Your Domain | |
| 77 | ||
| 78 | ```bash | |
| 79 | # Using AWS CLI | |
| 80 | aws ses verify-domain-identity --domain yourdomain.com | |
| 81 | ``` | |
| 82 | ||
| 83 | Add the verification TXT record to your DNS: | |
| 84 | ||
| 85 | ``` | |
| 86 | Type: TXT | |
| 87 | Name: _amazonses.yourdomain.com | |
| 88 | Value: <verification-token-from-aws> | |
| 89 | ``` | |
| 90 | ||
| 91 | ### Step 2: Configure DKIM | |
| 92 | ||
| 93 | ```bash | |
| 94 | aws ses verify-domain-dkim --domain yourdomain.com | |
| 95 | ``` | |
| 96 | ||
| 97 | Add CNAME records for DKIM: | |
| 98 | ||
| 99 | ``` | |
| 100 | <token1>._domainkey.yourdomain.com -> <token1>.dkim.amazonses.com | |
| 101 | <token2>._domainkey.yourdomain.com -> <token2>.dkim.amazonses.com | |
| 102 | <token3>._domainkey.yourdomain.com -> <token3>.dkim.amazonses.com | |
| 103 | ``` | |
| 104 | ||
| 105 | ### Step 3: Set Up MX Record for Receiving | |
| 106 | ||
| 107 | ``` | |
| 108 | Type: MX | |
| 109 | Name: yourdomain.com | |
| 110 | Value: 10 inbound-smtp.us-east-1.amazonaws.com | |
| 111 | ``` | |
| 112 | ||
| 113 | ## Sending Emails | |
| 114 | ||
| 115 | ### Basic Email | |
| 116 | ||
| 117 | ```ts | |
| 118 | import { mail } from '@stacksjs/email' | |
| 119 | ||
| 120 | await mail.send({ | |
| 121 | to: 'user@example.com', | |
| 122 | subject: 'Welcome to our app!', | |
| 123 | html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>', | |
| 124 | }) | |
| 125 | ``` | |
| 126 | ||
| 127 | ### Using Templates | |
| 128 | ||
| 129 | ```ts | |
| 130 | await mail.send({ | |
| 131 | to: 'user@example.com', | |
| 132 | subject: 'Welcome to our app!', | |
| 133 | template: 'welcome', | |
| 134 | data: { | |
| 135 | name: 'John', | |
| 136 | verificationUrl: 'https://yourapp.com/verify?token=abc123', | |
| 137 | }, | |
| 138 | }) | |
| 139 | ``` | |
| 140 | ||
| 141 | ### Template File | |
| 142 | ||
| 143 | ```html | |
| 144 | <!-- resources/emails/welcome.html --> | |
| 145 | <!DOCTYPE html> | |
| 146 | <html> | |
| 147 | <head> | |
| 148 | <style> | |
| 149 | .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; } | |
| 150 | .header { background: #4F46E5; color: white; padding: 20px; text-align: center; } | |
| 151 | .content { padding: 20px; } | |
| 152 | .button { display: inline-block; padding: 12px 24px; background: #4F46E5; color: white; text-decoration: none; border-radius: 6px; } | |
| 153 | </style> | |
| 154 | </head> | |
| 155 | <body> | |
| 156 | <div class="container"> | |
| 157 | <div class="header"> | |
| 158 | <h1>Welcome, {{ name }}!</h1> | |
| 159 | </div> | |
| 160 | <div class="content"> | |
| 161 | <p>Thanks for signing up. Please verify your email address:</p> | |
| 162 | <p><a href="{{ verificationUrl }}" class="button">Verify Email</a></p> | |
| 163 | </div> | |
| 164 | </div> | |
| 165 | </body> | |
| 166 | </html> | |
| 167 | ``` | |
| 168 | ||
| 169 | ### Sending with Attachments | |
| 170 | ||
| 171 | ```ts | |
| 172 | await mail.send({ | |
| 173 | to: 'user@example.com', | |
| 174 | subject: 'Your Invoice', | |
| 175 | template: 'invoice', | |
| 176 | data: { invoiceNumber: 'INV-001' }, | |
| 177 | attachments: [ | |
| 178 | { | |
| 179 | filename: 'invoice.pdf', | |
| 180 | content: pdfBuffer, | |
| 181 | contentType: 'application/pdf', | |
| 182 | }, | |
| 183 | ], | |
| 184 | }) | |
| 185 | ``` | |
| 186 | ||
| 187 | ### Bulk Emails | |
| 188 | ||
| 189 | ```ts | |
| 190 | import { mail } from '@stacksjs/email' | |
| 191 | ||
| 192 | const recipients = [ | |
| 193 | { email: 'user1@example.com', name: 'User 1' }, | |
| 194 | { email: 'user2@example.com', name: 'User 2' }, | |
| 195 | ] | |
| 196 | ||
| 197 | for (const recipient of recipients) { | |
| 198 | await mail.send({ | |
| 199 | to: recipient.email, | |
| 200 | subject: 'Newsletter', | |
| 201 | template: 'newsletter', | |
| 202 | data: { name: recipient.name }, | |
| 203 | }) | |
| 204 | ||
| 205 | // Add delay to respect rate limits | |
| 206 | await new Promise(resolve => setTimeout(resolve, 100)) | |
| 207 | } | |
| 208 | ``` | |
| 209 | ||
| 210 | ## Receiving Emails | |
| 211 | ||
| 212 | ### SES Receipt Rules | |
| 213 | ||
| 214 | Set up SES to store incoming emails in S3: | |
| 215 | ||
| 216 | ```ts | |
| 217 | // infrastructure/email-receiving.ts | |
| 218 | import _ as ses from 'aws-cdk-lib/aws-ses' | |
| 219 | import _ as actions from 'aws-cdk-lib/aws-ses-actions' | |
| 220 | import * as s3 from 'aws-cdk-lib/aws-s3' | |
| 221 | ||
| 222 | const emailBucket = new s3.Bucket(this, 'EmailBucket', { | |
| 223 | bucketName: 'your-email-bucket', | |
| 224 | }) | |
| 225 | ||
| 226 | const receiptRuleSet = new ses.ReceiptRuleSet(this, 'RuleSet', { | |
| 227 | receiptRuleSetName: 'default-rule-set', | |
| 228 | }) | |
| 229 | ||
| 230 | new ses.ReceiptRule(this, 'ReceiptRule', { | |
| 231 | ruleSet: receiptRuleSet, | |
| 232 | recipients: ['yourdomain.com'], | |
| 233 | actions: [ | |
| 234 | new actions.S3({ | |
| 235 | bucket: emailBucket, | |
| 236 | objectKeyPrefix: 'emails/', | |
| 237 | }), | |
| 238 | ], | |
| 239 | }) | |
| 240 | ``` | |
| 241 | ||
| 242 | ### Processing Incoming Emails | |
| 243 | ||
| 244 | ```ts | |
| 245 | import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3' | |
| 246 | import { simpleParser } from 'mailparser' | |
| 247 | ||
| 248 | const s3Client = new S3Client({ region: 'us-east-1' }) | |
| 249 | ||
| 250 | async function processIncomingEmail(bucketName: string, key: string) { | |
| 251 | const command = new GetObjectCommand({ | |
| 252 | Bucket: bucketName, | |
| 253 | Key: key, | |
| 254 | }) | |
| 255 | ||
| 256 | const response = await s3Client.send(command) | |
| 257 | const rawEmail = await response.Body?.transformToString() | |
| 258 | ||
| 259 | if (!rawEmail) return | |
| 260 | ||
| 261 | const parsed = await simpleParser(rawEmail) | |
| 262 | ||
| 263 | return { | |
| 264 | from: parsed.from?.text, | |
| 265 | to: parsed.to?.text, | |
| 266 | subject: parsed.subject, | |
| 267 | text: parsed.text, | |
| 268 | html: parsed.html, | |
| 269 | attachments: parsed.attachments, | |
| 270 | date: parsed.date, | |
| 271 | } | |
| 272 | } | |
| 273 | ``` | |
| 274 | ||
| 275 | ## Endless Email Addresses | |
| 276 | ||
| 277 | Once your domain is verified with SES, you can use any email address format: | |
| 278 | ||
| 279 | ### Service-Based Organization | |
| 280 | ||
| 281 | ``` | |
| 282 | facebook@yourdomain.com | |
| 283 | instagram@yourdomain.com | |
| 284 | linkedin@yourdomain.com | |
| 285 | ``` | |
| 286 | ||
| 287 | ### Using + for Organization | |
| 288 | ||
| 289 | The `+` character creates folder structures in S3: | |
| 290 | ||
| 291 | ``` | |
| 292 | accounts+social+facebook@yourdomain.com | |
| 293 | accounts+social+instagram@yourdomain.com | |
| 294 | accounts+travel+car+hertz@yourdomain.com | |
| 295 | accounts+money+paypal@yourdomain.com | |
| 296 | ``` | |
| 297 | ||
| 298 | ### Client Organization | |
| 299 | ||
| 300 | ``` | |
| 301 | clients+company_name+aws+account_name@yourdomain.com | |
| 302 | clients+company_name+stripe@yourdomain.com | |
| 303 | clients+company_name+sentry@yourdomain.com | |
| 304 | ``` | |
| 305 | ||
| 306 | ### Alert Organization | |
| 307 | ||
| 308 | ``` | |
| 309 | alarms+company_name+aws+account_name+alarm_type@yourdomain.com | |
| 310 | alarms+company_name+sentry+alarm_type@yourdomain.com | |
| 311 | ``` | |
| 312 | ||
| 313 | ## Email Queuing | |
| 314 | ||
| 315 | ### Queue Configuration | |
| 316 | ||
| 317 | ```ts | |
| 318 | // config/queue.ts | |
| 319 | export default { | |
| 320 | default: 'database', | |
| 321 | ||
| 322 | connections: { | |
| 323 | database: { | |
| 324 | driver: 'database', | |
| 325 | table: 'jobs', | |
| 326 | queue: 'default', | |
| 327 | retry_after: 90, | |
| 328 | }, | |
| 329 | }, | |
| 330 | } | |
| 331 | ``` | |
| 332 | ||
| 333 | ### Queue Email Jobs | |
| 334 | ||
| 335 | ```ts | |
| 336 | import { queue } from '@stacksjs/queue' | |
| 337 | ||
| 338 | interface SendEmailJob { | |
| 339 | to: string | |
| 340 | subject: string | |
| 341 | template: string | |
| 342 | data: Record<string, any> | |
| 343 | } | |
| 344 | ||
| 345 | // Queue an email | |
| 346 | await queue.push<SendEmailJob>('send-email', { | |
| 347 | to: 'user@example.com', | |
| 348 | subject: 'Welcome!', | |
| 349 | template: 'welcome', | |
| 350 | data: { name: 'John' }, | |
| 351 | }) | |
| 352 | ||
| 353 | // Process email jobs | |
| 354 | queue.process<SendEmailJob>('send-email', async (job) => { | |
| 355 | await mail.send({ | |
| 356 | to: job.data.to, | |
| 357 | subject: job.data.subject, | |
| 358 | template: job.data.template, | |
| 359 | data: job.data.data, | |
| 360 | }) | |
| 361 | }) | |
| 362 | ``` | |
| 363 | ||
| 364 | ## Email Tracking | |
| 365 | ||
| 366 | ### Track Opens | |
| 367 | ||
| 368 | ```ts | |
| 369 | async function sendTrackableEmail(userId: number, emailType: string) { | |
| 370 | const trackingId = randomUUIDv7() | |
| 371 | ||
| 372 | await EmailTracking.create({ | |
| 373 | id: trackingId, | |
| 374 | user_id: userId, | |
| 375 | email_type: emailType, | |
| 376 | sent_at: new Date().toISOString(), | |
| 377 | }) | |
| 378 | ||
| 379 | const trackingPixel = `<img src="${process.env.APP_URL}/api/email/track/${trackingId}" width="1" height="1" />` | |
| 380 | ||
| 381 | await mail.send({ | |
| 382 | to: user.email, | |
| 383 | subject: 'Your newsletter', | |
| 384 | html: `<p>Content here...</p>${trackingPixel}`, | |
| 385 | }) | |
| 386 | } | |
| 387 | ||
| 388 | // Tracking endpoint | |
| 389 | router.get('/api/email/track/:id', async (request) => { | |
| 390 | const { id } = request.params | |
| 391 | ||
| 392 | await EmailTracking.where('id', '=', id).update({ | |
| 393 | opened_at: new Date().toISOString(), | |
| 394 | }) | |
| 395 | ||
| 396 | // Return 1x1 transparent GIF | |
| 397 | const pixel = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64') | |
| 398 | ||
| 399 | return new Response(pixel, { | |
| 400 | headers: { | |
| 401 | 'Content-Type': 'image/gif', | |
| 402 | 'Cache-Control': 'no-store', | |
| 403 | }, | |
| 404 | }) | |
| 405 | }) | |
| 406 | ``` | |
| 407 | ||
| 408 | ### Track Clicks | |
| 409 | ||
| 410 | ```ts | |
| 411 | async function trackClickUrl(originalUrl: string, trackingId: string): string { | |
| 412 | const encodedUrl = encodeURIComponent(originalUrl) | |
| 413 | return `${process.env.APP_URL}/api/email/click/${trackingId}?url=${encodedUrl}` | |
| 414 | } | |
| 415 | ||
| 416 | router.get('/api/email/click/:id', async (request) => { | |
| 417 | const { id } = request.params | |
| 418 | const url = new URL(request.url) | |
| 419 | const redirectUrl = url.searchParams.get('url') | |
| 420 | ||
| 421 | await EmailClick.create({ | |
| 422 | tracking_id: id, | |
| 423 | url: redirectUrl, | |
| 424 | clicked_at: new Date().toISOString(), | |
| 425 | }) | |
| 426 | ||
| 427 | return Response.redirect(decodeURIComponent(redirectUrl!)) | |
| 428 | }) | |
| 429 | ``` | |
| 430 | ||
| 431 | ## Testing Emails | |
| 432 | ||
| 433 | ### Development Mode | |
| 434 | ||
| 435 | ```ts | |
| 436 | // Use log mailer in development | |
| 437 | // config/email.ts | |
| 438 | export default { | |
| 439 | default: process.env.NODE_ENV === 'development' ? 'log' : 'ses', | |
| 440 | } | |
| 441 | ``` | |
| 442 | ||
| 443 | ### Email Preview | |
| 444 | ||
| 445 | ```ts | |
| 446 | // Preview emails in browser during development | |
| 447 | router.get('/dev/email-preview/:template', async (request) => { | |
| 448 | if (process.env.NODE_ENV !== 'development') { | |
| 449 | return Response.json({ error: 'Not found' }, { status: 404 }) | |
| 450 | } | |
| 451 | ||
| 452 | const { template } = request.params | |
| 453 | ||
| 454 | const html = await renderEmailTemplate(template, { | |
| 455 | name: 'Test User', | |
| 456 | verificationUrl: 'https://example.com/verify', | |
| 457 | }) | |
| 458 | ||
| 459 | return new Response(html, { | |
| 460 | headers: { 'Content-Type': 'text/html' }, | |
| 461 | }) | |
| 462 | }) | |
| 463 | ``` | |
| 464 | ||
| 465 | ## Error Handling | |
| 466 | ||
| 467 | ```ts | |
| 468 | try { | |
| 469 | await mail.send({ | |
| 470 | to: 'user@example.com', | |
| 471 | subject: 'Hello', | |
| 472 | html: '<p>Content</p>', | |
| 473 | }) | |
| 474 | } catch (error) { | |
| 475 | if (error.code === 'MessageRejected') { | |
| 476 | console.error('Email rejected by SES:', error.message) | |
| 477 | } else if (error.code === 'InvalidParameterValue') { | |
| 478 | console.error('Invalid email parameter:', error.message) | |
| 479 | } else { | |
| 480 | console.error('Failed to send email:', error) | |
| 481 | } | |
| 482 | } | |
| 483 | ``` | |
| 484 | ||
| 485 | ## Best Practices | |
| 486 | ||
| 487 | 1. **Use templates** - Keep email content in separate template files | |
| 488 | 2. **Queue emails** - Don't send emails synchronously in request handlers | |
| 489 | 3. **Handle bounces** - Set up SNS notifications for bounces and complaints | |
| 490 | 4. **Respect rate limits** - SES has sending limits; add delays for bulk emails | |
| 491 | 5. **Validate addresses** - Verify email addresses before adding to mailing lists | |
| 492 | 6. **Test thoroughly** - Use the log mailer in development | |
| 493 | ||
| 494 | This documentation covers the essential email and mailbox functionality. Each function is designed for reliable email delivery using AWS SES. | |