### Local Development Setup and Test Source: https://github.com/inboundemail/inbound/blob/main/README.md Clone the repository, install dependencies, start the dev server, and test email webhooks locally using the provided command. ```bash # Clone and setup git clone https://github.com/R44VC0RP/inbound cd inbound bun install # Start the dev server bun run dev # Test email webhooks locally (no AWS needed) bun run inbound-webhook-test test@yourdomain.com ``` -------------------------------- ### Create Environment File Source: https://github.com/inboundemail/inbound/blob/main/packages/security-agent/README.md Copies the example environment file to a new file for local configuration. This is a prerequisite for starting the server. ```bash cp .env.example .env ``` -------------------------------- ### Configuration Example Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Example of setting environment variables for service URL, API key, and email domains before deployment. ```bash export SERVICE_API_URL=https://your-app.com export SERVICE_API_KEY=your-secret-key export EMAIL_DOMAINS=yourdomain.com,anotherdomain.com ./deploy.sh ``` -------------------------------- ### Install Inbound SDK with Bun Source: https://github.com/inboundemail/inbound/blob/main/docs/quickstart/getting-started.mdx Install the Inbound SDK using the Bun package manager. ```bash bun add inboundemail ``` -------------------------------- ### Install Inbound SDK with npm Source: https://github.com/inboundemail/inbound/blob/main/docs/quickstart/getting-started.mdx Install the Inbound SDK using the npm package manager. ```bash npm install inboundemail ``` -------------------------------- ### Install Inbound SDK with pnpm Source: https://github.com/inboundemail/inbound/blob/main/docs/quickstart/getting-started.mdx Install the Inbound SDK using the pnpm package manager. ```bash pnpm add inboundemail ``` -------------------------------- ### Install SDK using npm or bun Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Install the inboundemail SDK using your preferred package manager. ```bash npm install inboundemail # or bun add inboundemail ``` -------------------------------- ### Environment Variables Output Example Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Example of environment variables output after deployment, to be added to the .env file. ```bash # Add these to your .env file: S3_BUCKET_NAME=inbound-emails-123456789012-us-west-2 AWS_ACCOUNT_ID=123456789012 LAMBDA_FUNCTION_NAME=inbound-email-processor AWS_REGION=us-west-2 # Make sure you also have these (from your AWS credentials): # AWS_ACCESS_KEY_ID=your_access_key_here # AWS_SECRET_ACCESS_KEY=your_secret_key_here ``` -------------------------------- ### Install Inbound SDK with Yarn Source: https://github.com/inboundemail/inbound/blob/main/docs/quickstart/getting-started.mdx Install the Inbound SDK using the Yarn package manager. ```bash yarn add inboundemail ``` -------------------------------- ### Start Development Server Source: https://github.com/inboundemail/inbound/blob/main/packages/security-agent/README.md Starts the security-agent development server. By default, it listens on all interfaces on port 8788. ```bash bun run dev ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/inboundemail/inbound/blob/main/docs/README.md Install the Mintlify CLI globally using npm. This is required for local development. ```bash npm i -g mintlify ``` -------------------------------- ### Start Local Development Server Source: https://github.com/inboundemail/inbound/blob/main/docs/README.md Run the Mintlify development server from the root of your documentation directory. Ensure docs.json is present. ```bash mintlify dev ``` -------------------------------- ### Install Package Dependencies Source: https://github.com/inboundemail/inbound/blob/main/packages/security-agent/README.md Installs the necessary dependencies for the security-agent project. Navigate to the project directory before running. ```bash cd packages/security-agent bun install ``` -------------------------------- ### DNS Provider Setup Instructions Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-24-mail-from-domain-implementation.mdx Manual setup instructions for adding the required MX and TXT records to your DNS provider. These records are necessary for the MAIL FROM domain to function correctly. ```text 1. **MX Record**: `mail.yourdomain.com` โ `10 feedback-smtp.us-east-2.amazonses.com` 2. **TXT Record**: `mail.yourdomain.com` โ `v=spf1 include:amazonses.com ~all` ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/inboundemail/inbound/blob/main/packages/admin-manage/README.md Commands to start the development server using different package managers. Open http://localhost:3000 to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Install MCP Server Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/mcp.mdx Install the Inbound MCP server locally using npm, pnpm, or bun. This is required for self-hosting the server. ```bash npm install @inbound/mcp # or pnpm add @inbound/mcp # or bun add @inbound/mcp ``` -------------------------------- ### Initial UI Setup and Keyboard Hint Timer Source: https://github.com/inboundemail/inbound/blob/main/scripts/email-parsing/email-viewer.html Initializes the UI when the DOM is ready and sets a timer to fade out the keyboard navigation hint after 5 seconds. ```javascript // Initialize - show first email document.addEventListener('DOMContentLoaded', () => { updateUI(); }); // Also initialize immediately in case DOMContentLoaded already fired updateUI(); // Hide keyboard hint after 5 seconds setTimeout(() => { const hint = document.querySelector('.keyboard-hint'); if (hint) { hint.style.opacity = '0'; hint.style.transition = 'opacity 0.5s ease'; } }, 5000); ``` -------------------------------- ### Install Inbound CLI Source: https://github.com/inboundemail/inbound/blob/main/SKILL.md Install the Inbound CLI globally using npm. This command makes the 'inbound' executable available on your system. ```bash npm i -g inbound-cli ``` -------------------------------- ### Install Inbound Email and Better Auth Packages Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/better-auth.mdx Install the necessary packages for inbound email and better-auth. Ensure you are using version 0.20.0 or above for inboundemail. ```bash npm install inboundemail better-auth ``` -------------------------------- ### Install React Email Components Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/better-auth.mdx Install the `@react-email/components` package to use pre-built React Email templates for Better Auth events. ```bash npm install @react-email/components ``` -------------------------------- ### Elysia API Testing Setup Source: https://github.com/inboundemail/inbound/blob/main/AGENTS.md Provides a basic setup for testing Elysia API endpoints using `bun:test`. It includes a helper function `apiRequest` to make authenticated requests to the dev API. ```typescript import { describe, it, expect } from "bun:test"; const API_URL = "https://dev.inbound.new/api/e2"; async function apiRequest(endpoint: string, options: RequestInit = {}) { return fetch(`${API_URL}${endpoint}`, { ...options, headers: { Authorization: `Bearer ${process.env.INBOUND_API_KEY}`, "Content-Type": "application/json", ...options.headers, }, }); } describe("Domains API", () => { it("should list domains", async () => { const response = await apiRequest("/domains"); expect(response.status).toBe(200); }); }); ``` -------------------------------- ### Manual State Management Example (Before Migration) Source: https://github.com/inboundemail/inbound/blob/main/features/README.md Illustrates the manual state management approach using useState and useEffect for data fetching. This pattern is being replaced by React Query hooks. ```typescript const [data, setData] = useState(null) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) useEffect(() => { fetchData() }, []) const fetchData = async () => { try { setIsLoading(true) const response = await fetch('/api/data') const data = await response.json() setData(data) } catch (error) { setError(error) } finally { setIsLoading(false) } } ``` -------------------------------- ### Troubleshooting Build Errors Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Commands to help resolve build errors, including installing dependencies and checking TypeScript compilation. ```bash npm install npm run build ``` -------------------------------- ### Client Setup for Type Inference Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/better-auth.mdx Set up the Better Auth client on the client side to enable proper type inference when using the inbound email plugin. ```typescript import { createAuthClient } from 'better-auth/react'; import { inboundEmailClientPlugin } from 'inboundemail/better-auth/client'; export const authClient = createAuthClient({ plugins: [inboundEmailClientPlugin()], }); ``` -------------------------------- ### Verify Inbound CLI Command Source: https://github.com/inboundemail/inbound/blob/main/SKILL.md Check if the 'inbound' command is installed and accessible by running the help command. This confirms the CLI is ready for use. ```bash inbound help ``` -------------------------------- ### Example Backfill Script Output Source: https://github.com/inboundemail/inbound/blob/main/scripts/email-threading/README.md This output demonstrates the progress and final statistics of the email threading backfill script. It shows the options used, emails processed, threads created, and overall performance. ```text ๐งต Starting email threading backfill... ๐ Options: batchSize=100, maxEmails=unlimited, dryRun=false, userId=all users ๐ง Found 1,234 emails to process ๐ฆ Processing batch 1 (emails 1-100) ๐ Processing email abc123 (Welcome to our service...) ๐ Created new thread thread_xyz789 ๐ Processing email def456 (Re: Welcome to our service...) ๐ Added to existing thread thread_xyz789 at position 2 ... โ Backfill completed! ๐ Final Statistics: Total emails: 1,234 Processed: 1,234 Threads created: 456 Emails threaded: 1,234 Errors: 0 Duration: 123 seconds Rate: 10 emails/second ``` -------------------------------- ### Server Setup with Inbound Email Plugin Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/better-auth.mdx Configure the Better Auth instance on the server to include the inbound email plugin. This requires an Inbound API key and a default 'from' email address. ```typescript import { betterAuth } from 'better-auth'; import { inboundEmailPlugin } from 'inboundemail/better-auth'; export const auth = betterAuth({ // ... your Better Auth config plugins: [ inboundEmailPlugin({ client: { apiKey: process.env.INBOUND_API_KEY! }, from: 'security@yourdomain.com', }), ], }); ``` -------------------------------- ### Email Data Structure Example Source: https://github.com/inboundemail/inbound/blob/main/scripts/email-parsing/email-viewer.html An example of the JSON structure expected for email data. This includes subject, sender, recipient, date, and body. ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "subject": "Meeting Reminder", "from": "sender@example.com", "to": "recipient@example.com", "date": "2023-10-27T10:00:00Z", "body": "
Hi there,
Just a reminder about our meeting tomorrow at 10 AM.
" } ``` -------------------------------- ### Configure Mixed Mode Email Routing Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-24-mixed-email-routing.mdx Example configuration demonstrating how to set up specific email addresses alongside a catch-all endpoint. Specific addresses are routed to their designated webhooks, while all other emails fall back to the general webhook. ```typescript // Your domain now supports both: const specificEmails = [ { address: 'support@yourdomain.com', endpoint: 'support-webhook' }, { address: 'sales@yourdomain.com', endpoint: 'sales-webhook' } ] const catchAllConfig = { enabled: true, endpoint: 'general-webhook' } // Routing behavior: // support@yourdomain.com โ support-webhook // sales@yourdomain.com โ sales-webhook // anything-else@yourdomain.com โ general-webhook ``` -------------------------------- ### Send Email using Node.js Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/introduction.mdx Send emails programmatically using Node.js. This example is similar to the Resend SDK. ```typescript const { data, error } = await inbound.emails.send({ from: 'Inbound UserThanks for signing up!
', tags: [{ name: 'campaign', value: 'welcome' }] }) console.log(`Email sent: ${data?.id}`) ``` -------------------------------- ### Complete Webhook Example with Verification Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/webhook.mdx This snippet demonstrates how to verify webhook authenticity using `verifyWebhookFromHeaders` and then process the incoming email payload, including handling attachments. It's suitable for a production environment requiring secure webhook handling. ```typescript import { Inbound, verifyWebhookFromHeaders, type InboundWebhookPayload } from 'inboundemail' const inbound = new Inbound(process.env.INBOUND_API_KEY!) export async function POST(request: Request) { // Step 1: Verify webhook authenticity const isValid = await verifyWebhookFromHeaders(request.headers, inbound) if (!isValid) { console.warn('Webhook verification failed', { endpointId: request.headers.get('X-Endpoint-ID'), timestamp: new Date().toISOString() }) return new Response('Unauthorized', { status: 401 }) } // Step 2: Parse verified payload const payload: InboundWebhookPayload = await request.json() const { email, endpoint } = payload // Step 3: Process the email console.log(`Received email from ${email.from.addresses[0].address}`) console.log(`Subject: ${email.subject}`) console.log(`Endpoint: ${endpoint.name}`) // Step 4: Handle attachments if present if (email.parsedData.attachments?.length > 0) { for (const attachment of email.parsedData.attachments) { // Download attachment using the provided downloadUrl const response = await fetch(attachment.downloadUrl, { headers: { 'Authorization': `Bearer ${process.env.INBOUND_API_KEY}` } }) if (response.ok) { const fileBuffer = await response.arrayBuffer() // Process attachment... } } } return new Response('OK', { status: 200 }) } ``` -------------------------------- ### Set Environment Variables Before CDK Deployment Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/ENVIRONMENT_SETUP.md Set the required environment variables in your shell before running the CDK deploy command. This is the recommended approach for environment setup. ```bash export SERVICE_API_URL="https://inbound.exon.dev" export SERVICE_API_KEY="your-secret-api-key-here" # Then deploy cd aws/cdk bun run deploy ``` -------------------------------- ### Verify Webhook with SDK Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/webhook.mdx This example shows how to verify the authenticity of an incoming webhook request using the Inbound SDK's `verifyWebhookFromHeaders` function. It's crucial to perform this verification before processing any payload to ensure security. ```typescript import { Inbound, verifyWebhookFromHeaders } from 'inboundemail' const inbound = new Inbound(process.env.INBOUND_API_KEY!) export async function POST(request: Request) { // Verify webhook authenticity before processing const isValid = await verifyWebhookFromHeaders(request.headers, inbound) if (!isValid) { return new Response('Unauthorized', { status: 401 }) } // Process the verified webhook payload const payload: InboundWebhookPayload = await request.json() const { email } = payload // Your webhook handling logic here console.log('Received verified email:', email.subject) return new Response('OK', { status: 200 }) } ``` -------------------------------- ### Claude Desktop MCP Configuration Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/mcp.mdx Configure Claude Desktop to use the Inbound MCP server. This setup uses STDIO transport and runs the MCP server locally via npx. Replace 'your-api-key' with your actual Inbound API key. ```json { "mcpServers": { "inbound": { "command": "npx", "args": ["-y", "@inbound/mcp"], "env": { "INBOUND_API_KEY": "your-api-key" } } } } ``` -------------------------------- ### Full Configuration Options for Inbound Email Plugin Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/better-auth.mdx Explore all available configuration options for the inboundEmailPlugin, including client setup, default sender, event-specific configurations, and lifecycle hooks. ```typescript inboundEmailPlugin({ // Required: Inbound client or API key client: { apiKey: process.env.INBOUND_API_KEY! }, // Or pass an existing client instance: // client: new Inbound({ apiKey: '...' }), // Required: Default "from" address for all emails from: 'security@yourdomain.com', // Optional: Include device info in new sign-in emails (default: true) includeDeviceInfo: true, // Optional: Configure specific events events: { 'password-changed': { enabled: true, from: 'alerts@yourdomain.com', // Override from address template: customTemplate, // Custom template function }, 'password-reset-requested': { enabled: true, // Enable this disabled-by-default event }, }, // Optional: Lifecycle hooks onBeforeSend: async (event, context, email) => { // Return false to cancel sending return true; }, onAfterSend: async (event, context, result) => { console.log(`Sent ${event} email:`, result.id); }, onError: async (event, context, error) => { console.error(`Failed to send ${event} email:`, error); }, }); ``` -------------------------------- ### Test Webhook Endpoint Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/ENVIRONMENT_SETUP.md Perform a GET request to your webhook endpoint to verify it is accessible and returning a health check response. Replace 'your-domain.com' with your actual domain. ```bash curl -X GET https://your-domain.com/api/inbound/webhook ``` -------------------------------- ### Manual Deployment Steps Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Steps for manual deployment including building, deploying, and checking stack outputs. ```bash cd aws/cdk npm install npm run build npm run deploy ``` ```bash aws cloudformation describe-stacks --stack-name InboundEmailStack --query 'Stacks[0].Outputs' ``` -------------------------------- ### Full Deployment Script Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Recommended script for building and deploying the CDK stack. It also extracts necessary environment variables. ```bash cd aws/cdk npm install ./deploy.sh ``` -------------------------------- ### Simple Deployment Script Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md A simpler deployment script that does not require 'jq' and displays raw CDK outputs. ```bash cd aws/cdk npm install ./deploy-simple.sh ``` -------------------------------- ### Get Specific Received Email Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Retrieve a specific received email by its unique ID. ```javascript // Get specific email const email = await inbound.mail.get(emailId) ``` -------------------------------- ### Get Email Details Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Retrieve detailed information about a specific sent email using its ID. ```javascript // Get email details const details = await inbound.emails.get(emailId) ``` -------------------------------- ### Initialize Inbound Client Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Instantiate the Inbound client with your API key. This is the first step to interacting with the SDK. ```javascript import { Inbound } from '@inboundemail/sdk' const inbound = new Inbound('your-api-key') ``` -------------------------------- ### API Error Response Example Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/introduction.mdx API errors are returned with appropriate HTTP status codes and a JSON body detailing the error. ```json { "error": "Invalid or missing API key" } ``` -------------------------------- ### Webhook Helper Functions Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Utilize helper functions to validate webhook payloads, extract sender information, and get email text content. ```javascript import { isInboundWebhook, getSenderInfo, getEmailText } from '@inboundemail/sdk' // Validate webhook payload if (isInboundWebhook(payload)) { const sender = getSenderInfo(payload.email) const text = getEmailText(payload.email) } ``` -------------------------------- ### Sample Curl Request for /run Endpoint Source: https://github.com/inboundemail/inbound/blob/main/packages/security-agent/README.md Demonstrates how to call the POST /run endpoint using curl with bearer authentication and a JSON payload for the /abuse-block command. ```bash curl -sS -X POST http://localhost:8788/run \ -H "Authorization: Bearer $SERVICE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "command":"/abuse-block", "args":"--tenant-id tnt_123 --action cascade --execute --auto-confirm --reason \"abuse threshold exceeded\"" }' ``` -------------------------------- ### Retrieve Endpoint Verification Token Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/security.mdx Get the verification token for a specific endpoint using the Inbound SDK. This is useful for managing or displaying the token in your application. ```typescript import { Inbound } from 'inboundemail' const inbound = new Inbound(process.env.INBOUND_API_KEY!) // Get endpoint configuration const { data: endpoint } = await inbound.endpoint.get('your-endpoint-id') if (endpoint) { const config = typeof endpoint.config === 'string' ? JSON.parse(endpoint.config) : endpoint.config console.log('Verification token:', config.verificationToken) } ``` -------------------------------- ### Re-install Mintlify Dependencies Source: https://github.com/inboundemail/inbound/blob/main/docs/README.md If 'mintlify dev' is not running, use this command to re-install dependencies. This can resolve issues with the development server. ```bash mintlify install ``` -------------------------------- ### Get Specific Email Thread Source: https://github.com/inboundemail/inbound/blob/main/SKILL.md Retrieve the details of a specific email thread using its unique ID. Replace 'Hello, I need help with my recent order...
', raw: 'From: john@example.com\r\nTo: support@yourdomain.com\r\n...', attachments: [ { filename: 'order-receipt.pdf', contentType: 'application/pdf', size: 45678, contentId: 'Hello, I need help with my recent order...
', text: 'Hello, I need help with my recent order...', hasHtml: true, hasText: true, attachments: [ { filename: 'order-receipt.pdf', contentType: 'application/pdf', size: 45678, contentId: 'This is my first email with Inbound.
' }) if (error) { console.error('Error:', error) } else { console.log('Email sent:', data?.id) } ``` -------------------------------- ### Run Backfill Script (Dry Run) Source: https://github.com/inboundemail/inbound/blob/main/scripts/email-threading/README.md Execute the backfill script in dry run mode to preview changes without modifying data. This is useful for testing. ```bash bun run scripts/email-threading/backfill-threads.ts --dry-run ``` -------------------------------- ### Create and Source .env File for CDK Deployment Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/ENVIRONMENT_SETUP.md Create a .env file in the aws/cdk directory to store environment variables and source it before deployment. This method is useful for managing environment-specific configurations. ```bash SERVICE_API_URL=https://inbound.exon.dev SERVICE_API_KEY=your-secret-api-key-here ``` ```bash cd aws/cdk source .env bun run deploy ``` -------------------------------- ### Run Backfill Script (Specific User) Source: https://github.com/inboundemail/inbound/blob/main/scripts/email-threading/README.md Process emails for a single user to create thread relationships. This helps isolate the backfill process. ```bash bun run scripts/email-threading/backfill-threads.ts --user-id user123 ``` -------------------------------- ### Check All Domains with AWS SES Status Helper Source: https://github.com/inboundemail/inbound/blob/main/security-review.md Use this command to retrieve status information for all domains, with an optional limit on the number of results. Requires AWS credentials and optionally an AWS region and account ID. ```bash bun run scripts/aws-ses-status-helper.ts --all-domains --limit 100 ``` -------------------------------- ### Initialize Inbound Interface Source: https://github.com/inboundemail/inbound/blob/main/content/blog/getting-started-with-inbound.mdx This snippet shows how to create a new instance of the Inbound interface. Ensure the Interface class is properly imported or defined before use. ```typescript const newThing = new Interface() ``` -------------------------------- ### OpenCode MCP Configuration Source: https://github.com/inboundemail/inbound/blob/main/docs/integrations/mcp.mdx Add this configuration to your OpenCode JSON file to connect to the Inbound MCP server. Replace 'your-api-key' with your actual Inbound API key. ```json { "mcp": { "inbound": { "type": "remote", "url": "https://mcp.inbound.new/mcp", "headers": { "x-inbound-api-key": "your-api-key" } } } } ``` -------------------------------- ### React Query Hook Usage (After Migration) Source: https://github.com/inboundemail/inbound/blob/main/features/README.md Demonstrates the simplified component structure after migrating to React Query. State management (data, loading, error) and refetching are handled by the hook. ```typescript const { data, isLoading, error, refetch } = useDataQuery() ``` -------------------------------- ### Create an Email Address Source: https://github.com/inboundemail/inbound/blob/main/README.md Create a programmable email address and associate it with a webhook URL for receiving emails. Ensure the domain is already added. ```javascript const emailAddress = await inbound.emailAddresses.create({ address: "hello@yourdomain.com", webhookUrl: "https://yourapp.com/webhook/email" }) console.log("Email address created:", emailAddress.address) ``` -------------------------------- ### Receive Emails with Endpoint Routing Logic Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/introduction.mdx Illustrates a basic switch-case logic for routing incoming emails to different endpoints based on the email address. ```typescript switch (email) { case 'support@yourdomain.com': endpoint1 // Specific endpoint for support case 'sales@yourdomain.com': endpoint2 // Specific endpoint for sales default: // catch-all endpoint3 // Fallback endpoint for all other emails } ``` -------------------------------- ### Cleanup Command Source: https://github.com/inboundemail/inbound/blob/main/aws/cdk/README.md Command to remove all deployed resources. ```bash npm run destroy ``` -------------------------------- ### Complete Ban Workflow Script Source: https://github.com/inboundemail/inbound/blob/main/AGENTS.md A script demonstrating the complete ban workflow, including tenant suspension and scheduled email cleanup. ```TypeScript scripts/ban-user.ts ``` -------------------------------- ### Send First Email with TypeScript SDK Source: https://github.com/inboundemail/inbound/blob/main/docs/api-reference/introduction.mdx Send your first email using the Inbound TypeScript SDK. Ensure your API key is set as an environment variable. ```typescript import { Inbound } from 'inboundemail' const inbound = new Inbound(process.env.INBOUND_API_KEY!) const { data, error } = await inbound.emails.send({ from: 'Inbound UserThanks for signing up!
', tags: [{ name: 'campaign', value: 'welcome' }] }) console.log(`Email sent: ${data?.id}`) ``` -------------------------------- ### Import TypeScript Definitions Source: https://github.com/inboundemail/inbound/blob/main/app/changelog/entries/2025-01-20-sdk-v2-release.mdx Import type definitions for various SDK components. Essential for leveraging TypeScript's static typing. ```typescript import type { InboundWebhookPayload, InboundWebhookEmail, CreateEndpointParams, Domain } from '@inboundemail/sdk' ``` -------------------------------- ### Add a Domain Source: https://github.com/inboundemail/inbound/blob/main/README.md Create a new domain within the Inbound service. This is necessary before creating email addresses. ```javascript const domain = await inbound.domains.create({ domain: "yourdomain.com" }) console.log("Domain added:", domain.domain) ``` -------------------------------- ### Receive and Reply to Emails Source: https://github.com/inboundemail/inbound/blob/main/README.md This snippet demonstrates how to set up a webhook to receive incoming emails and automatically reply based on subject content. It includes validation for Inbound webhooks. ```javascript import { Inbound, type InboundWebhookPayload, isInboundWebhookPayload } from 'inboundemail' import { NextRequest, NextResponse } from 'next/server' const inbound = new Inbound(process.env.INBOUND_API_KEY!) export async function POST(request: NextRequest) { try { const payload: InboundWebhookPayload = await request.json() // Verify this is a valid Inbound webhook if (!isInboundWebhookPayload(payload)) { return NextResponse.json({ error: 'Invalid webhook' }, { status: 400 }) } const { email } = payload console.log(`๐ง Received email: ${email.subject} from ${email.from?.addresses?.[0]?.address}`) // Auto-reply to support emails if (email.subject?.toLowerCase().includes('support')) { await inbound.reply(email, { from: 'support@yourdomain.com', text: 'Thanks for contacting support! We\'ll get back to you within 24 hours.', tags: [{ name: 'type', value: 'auto-reply' }] }) } // Auto-reply to thank you emails if (email.subject?.toLowerCase().includes('thanks')) { await inbound.reply(email, { from: 'hello@yourdomain.com', html: 'You\'re welcome! Let us know if you need anything else.
' }) } return NextResponse.json({ success: true }) } catch (error) { console.error('Webhook error:', error) return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 }) } } ```