ReviewOS

also looking at this

loghqorg/loghq

Deploy: uniform auth session model (main → production)

#7
Merged glennmichael123 wants to merge main into production
282 files +3028 -64856
docs/bootcamp/how-to/create-mailbox.mddeleted+0-494
Changes to docs/bootcamp/how-to/create-mailbox.md
@@ -1,494 +0,0 @@
1# Create Mailbox
2
3This 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
7Stacks 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
23MAIL_MAILER=ses
24MAIL_FROM_ADDRESS=hello@yourdomain.com
25MAIL_FROM_NAME="Your App Name"
26
27# AWS SES Configuration
28AWS_ACCESS_KEY_ID=your_access_key
29AWS_SECRET_ACCESS_KEY=your_secret_key
30AWS_DEFAULT_REGION=us-east-1
31
32# Optional: Custom SMTP
33MAIL_HOST=smtp.mailtrap.io
34MAIL_PORT=587
35MAIL_USERNAME=your_username
36MAIL_PASSWORD=your_password
37MAIL_ENCRYPTION=tls
38```
39
40### Mail Configuration
41
42```ts
43// config/email.ts
44export 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
80aws ses verify-domain-identity --domain yourdomain.com
81```
82
83Add the verification TXT record to your DNS:
84
85```
86Type: TXT
87Name: _amazonses.yourdomain.com
88Value: <verification-token-from-aws>
89```
90
91### Step 2: Configure DKIM
92
93```bash
94aws ses verify-domain-dkim --domain yourdomain.com
95```
96
97Add 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```
108Type: MX
109Name: yourdomain.com
110Value: 10 inbound-smtp.us-east-1.amazonaws.com
111```
112
113## Sending Emails
114
115### Basic Email
116
117```ts
118import { mail } from '@stacksjs/email'
119
120await 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
130await 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
172await 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
190import { mail } from '@stacksjs/email'
191
192const recipients = [
193 { email: 'user1@example.com', name: 'User 1' },
194 { email: 'user2@example.com', name: 'User 2' },
195]
196
197for (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
214Set up SES to store incoming emails in S3:
215
216```ts
217// infrastructure/email-receiving.ts
218import _ as ses from 'aws-cdk-lib/aws-ses'
219import _ as actions from 'aws-cdk-lib/aws-ses-actions'
220import * as s3 from 'aws-cdk-lib/aws-s3'
221
222const emailBucket = new s3.Bucket(this, 'EmailBucket', {
223 bucketName: 'your-email-bucket',
224})
225
226const receiptRuleSet = new ses.ReceiptRuleSet(this, 'RuleSet', {
227 receiptRuleSetName: 'default-rule-set',
228})
229
230new 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
245import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'
246import { simpleParser } from 'mailparser'
247
248const s3Client = new S3Client({ region: 'us-east-1' })
249
250async 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
277Once your domain is verified with SES, you can use any email address format:
278
279### Service-Based Organization
280
281```
282facebook@yourdomain.com
283instagram@yourdomain.com
284linkedin@yourdomain.com
285```
286
287### Using + for Organization
288
289The `+` character creates folder structures in S3:
290
291```
292accounts+social+facebook@yourdomain.com
293accounts+social+instagram@yourdomain.com
294accounts+travel+car+hertz@yourdomain.com
295accounts+money+paypal@yourdomain.com
296```
297
298### Client Organization
299
300```
301clients+company_name+aws+account_name@yourdomain.com
302clients+company_name+stripe@yourdomain.com
303clients+company_name+sentry@yourdomain.com
304```
305
306### Alert Organization
307
308```
309alarms+company_name+aws+account_name+alarm_type@yourdomain.com
310alarms+company_name+sentry+alarm_type@yourdomain.com
311```
312
313## Email Queuing
314
315### Queue Configuration
316
317```ts
318// config/queue.ts
319export 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
336import { queue } from '@stacksjs/queue'
337
338interface SendEmailJob {
339 to: string
340 subject: string
341 template: string
342 data: Record<string, any>
343}
344
345// Queue an email
346await 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
354queue.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
369async 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
389router.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
411async 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
416router.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
438export 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
447router.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
468try {
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
4871. **Use templates** - Keep email content in separate template files
4882. **Queue emails** - Don't send emails synchronously in request handlers
4893. **Handle bounces** - Set up SNS notifications for bounces and complaints
4904. **Respect rate limits** - SES has sending limits; add delays for bulk emails
4915. **Validate addresses** - Verify email addresses before adding to mailing lists
4926. **Test thoroughly** - Use the log mailer in development
493
494This documentation covers the essential email and mailbox functionality. Each function is designed for reliable email delivery using AWS SES.