### Install Inbound SDK using Package Managers Source: https://docs.inbound.new/sdk/installation Install the latest Inbound SDK using npm, yarn, pnpm, or bun. This ensures you have the most recent version for your project. Ensure you have Node.js 18.0 or later installed. ```bash npm install @inboundemail/sdk@latest ``` ```bash yarn add @inboundemail/sdk@latest ``` ```bash pnpm add @inboundemail/sdk@latest ``` ```bash bun add @inboundemail/sdk@latest ``` -------------------------------- ### Import and Initialize Inbound SDK (TypeScript) Source: https://docs.inbound.new/sdk/installation Import the Inbound SDK and initialize it with your API key. The constructor now accepts the API key as a string. Optionally, you can specify a custom base URL for the API endpoint. This setup is crucial before sending any emails. ```typescript import { Inbound } from '@inboundemail/sdk' const inbound = new Inbound(process.env.INBOUND_API_KEY!) ``` ```typescript const inbound = new Inbound( process.env.INBOUND_API_KEY!, 'https://custom.inbound.url/api/v2' ) ``` -------------------------------- ### Send First Email using Inbound SDK (TypeScript) Source: https://docs.inbound.new/sdk/installation Send your first email using the Inbound SDK after initialization. This example demonstrates setting the sender, recipient, subject, HTML content, and tags. The `send` method returns a promise that resolves with the email details, including its ID. ```typescript const email = await inbound.emails.send({ from: 'hello@yourdomain.com', to: 'user@example.com', subject: 'Welcome!', html: '
Thanks for signing up!
', tags: [{ name: 'campaign', value: 'welcome' }] }) console.log(`Email sent: ${email.id}`) ``` -------------------------------- ### Install Inbound Email SDK with npm, yarn, pnpm, or bun Source: https://docs.inbound.new/sdk/quickstart Installs the official Inbound Email SDK using various package managers. This is the first step to integrating the SDK into your project. ```bash npm install @inboundemail/sdk ``` ```bash yarn add @inboundemail/sdk ``` ```bash pnpm add @inboundemail/sdk ``` ```bash bun add @inboundemail/sdk ``` -------------------------------- ### Migrate Inbound SDK Constructor from v2.x to v3.x (TypeScript) Source: https://docs.inbound.new/sdk/installation Compare the constructor syntax for Inbound SDK between v2.x and v3.x. The v3.x constructor simplifies initialization by directly accepting the API key as a string, with the base URL as an optional second argument, unlike the v2.x object-based configuration. ```typescript // v2.x (OLD) const inbound = new Inbound({ apiKey: process.env.INBOUND_API_KEY!, baseUrl: 'https://custom.url', defaultReplyFrom: 'support@domain.com' }) // v3.x (NEW) const inbound = new Inbound( process.env.INBOUND_API_KEY!, 'https://custom.url' // optional ) ``` -------------------------------- ### Testing Webhooks Locally with ngrok Source: https://docs.inbound.new/sdk/webhook-handling Provides command-line instructions for setting up ngrok to test inbound email webhooks locally. This involves installing ngrok, starting the local development server, and then exposing it to the internet via ngrok. ```bash # Install ngrok npm install -g ngrok # Start your local server npm run dev # In another terminal, expose your local server ngrok http 3000 # Use the ngrok URL for your webhook endpoint # https://abc123.ngrok.io/api/webhook ``` -------------------------------- ### Migrate Reply Method from v2.x to v3.x (TypeScript) Source: https://docs.inbound.new/sdk/installation Understand the updated `reply` method signature in Inbound SDK v3.x compared to v2.x. v2.x allowed simple string replies, whereas v3.x requires an explicit `from` address along with the email content (text or html) for more controlled replies. ```typescript // v2.x (OLD) - simple string replies await inbound.reply(email, "Thanks!") // v3.x (NEW) - explicit from address required await inbound.reply(email, { from: 'support@domain.com', text: 'Thanks!' }) ``` -------------------------------- ### Setup Domain, Endpoint, and Email Addresses with TypeScript Source: https://docs.inbound.new/sdk/examples Configures a new email domain, sets up a webhook endpoint for receiving emails, and creates standard email addresses. It includes waiting for domain verification and handling DNS records. Dependencies: @inboundemail/sdk. Inputs: domainName (string), webhookUrl (string). Outputs: Object containing verified domain, webhook, and addresses. ```typescript import { Inbound } from '@inboundemail/sdk' import type { DomainWithStats, EndpointWithStats, EmailAddressWithDomain } from '@inboundemail/sdk' export class EmailService { private inbound: Inbound constructor() { this.inbound = new Inbound({ apiKey: process.env.INBOUND_API_KEY!, defaultReplyFrom: 'noreply@yourdomain.com' }) } /** * Complete setup for a new domain */ async setupDomain(domainName: string, webhookUrl: string) { // 1. Add domain console.log('Adding domain...') const domain = await this.inbound.domains.create({ domain: domainName }) console.log('DNS Records to add:') domain.dnsRecords.forEach(record => { console.log(`${record.type} ${record.name} → ${record.value}`) }) // 2. Create webhook endpoint console.log('\nCreating webhook endpoint...') const webhook = await this.inbound.endpoints.create({ name: `${domainName} Webhook`, type: 'webhook', description: `Main webhook for ${domainName}`, config: { url: webhookUrl, timeout: 30, retryAttempts: 3, headers: { 'X-Domain': domainName, 'X-API-Key': process.env.WEBHOOK_SECRET! } } }) // 3. Wait for domain verification console.log('\nWaiting for domain verification...') const verifiedDomain = await this.waitForVerification(domain.id) // 4. Enable catch-all console.log('\nEnabling catch-all...') await this.inbound.domains.update(domain.id, { isCatchAllEnabled: true, catchAllEndpointId: webhook.id }) // 5. Create specific email addresses console.log('\nCreating email addresses...') const addresses = await this.createStandardAddresses( domainName, domain.id, webhook.id ) return { domain: verifiedDomain, webhook, addresses } } /** * Wait for domain verification with timeout */ private async waitForVerification( domainId: string, maxAttempts = 30 ): PromiseThanks for signing up.
', text: 'Welcome! Thanks for signing up.' }); if (error) { console.error('Error:', error); } else { console.log('Email sent:', data.id); } ``` ```bash curl -X POST 'https://inbound.new/api/v2/emails' \ -H 'Authorization: Bearer your_api_key' \ -H 'Content-Type: application/json' \ -d '{ "from": "AcmeThanks for signing up.
", "text": "Welcome! Thanks for signing up." }' ``` ```python import requests response = requests.post( 'https://inbound.new/api/v2/emails', headers={ 'Authorization': 'Bearer your_api_key', 'Content-Type': 'application/json', }, json={ 'from': 'AcmeThanks for signing up.
', 'text': 'Welcome! Thanks for signing up.' } ) print(response.json()) ``` ```php $ch = curl_init('https://inbound.new/api/v2/emails'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer your_api_key', 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'from' => 'AcmeThanks for signing up.
', 'text' => 'Welcome! Thanks for signing up.' ])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ``` -------------------------------- ### DNS DMARC Record Example Source: https://docs.inbound.new/api-reference/domains/get-dns-records Example of a DMARC (Domain-based Message Authentication, Reporting & Conformance) TXT DNS record, used for email authentication policy to guide receiving servers on handling SPF/DKIM failures. ```dns Name: _dmarc.example.com Value: v=DMARC1; p=none; rua=mailto:dmarc@example.com; ruf=mailto:dmarc@example.com; fo=1; aspf=r; adkim=r ``` -------------------------------- ### Replace mail.* Methods with email.received.* Source: https://docs.inbound.new/sdk/migration-guide Illustrates the replacement of deprecated mail.* methods with their recommended email.received.* counterparts. This example shows how to list emails, get details, mark as read, and reply to messages. ```typescript // ❌ Before (deprecated but still works) async function oldWay() { const emails = await inbound.mail.list({ limit: 50 }) for (const email of emails.emails) { const details = await inbound.mail.get(email.id) if (!email.isRead) { await inbound.mail.markRead(email.id) } if (details.subject.includes('urgent')) { await inbound.mail.reply({ emailId: email.id, to: details.from, subject: `Re: ${details.subject}`, textBody: 'Thank you for your urgent message.' }) } } } // ✅ After (recommended) async function newWay() { const emails = await inbound.email.received.list({ limit: 50 }) for (const email of emails.emails) { const details = await inbound.email.received.get(email.id) if (!email.isRead) { await inbound.email.received.markRead(email.id) } if (details.subject.includes('urgent')) { await inbound.email.received.reply({ emailId: email.id, to: details.from, subject: `Re: ${details.subject}`, textBody: 'Thank you for your urgent message.' }) } } } ``` -------------------------------- ### Domain & Configuration Management with Inbound API Source: https://docs.inbound.new/sdk/quickstart Illustrates how to manage domains, endpoints (like webhooks), and email addresses within the Inbound API. Requires appropriate configuration objects and IDs. ```javascript // Manage domains await inbound.domain.create({ domain: 'example.com' }) await inbound.domain.list() await inbound.domain.get('domain_id') // Manage endpoints await inbound.endpoint.create({ name: 'Webhook', type: 'webhook', config: {...} }) await inbound.endpoint.list() // Manage email addresses await inbound.email.address.create({ address: 'hello@domain.com', domainId: 'id' }) await inbound.email.address.list() ``` -------------------------------- ### DNS CNAME Record Example Source: https://docs.inbound.new/api-reference/domains/get-dns-records Example of a CNAME (Canonical Name) DNS record, sometimes used for specific subdomain configurations, mapping an alias to a canonical name. ```dns Name: mail.example.com Value: inbound-smtp.us-east-1.amazonaws.com ``` -------------------------------- ### DNS TXT Record Example Source: https://docs.inbound.new/api-reference/domains/get-dns-records Example of a TXT DNS record, commonly used for domain verification and AWS SES identity verification. It includes the record's name and value. ```dns Name: _amazonses.example.com Value: abc123def456ghi789jkl ``` -------------------------------- ### DNS MX Record Example Source: https://docs.inbound.new/api-reference/domains/get-dns-records Example of an MX (Mail Exchanger) DNS record, used for routing emails to the correct mail servers. It specifies the record's name, value, and priority. ```dns Name: example.com Value: 10 inbound-smtp.us-east-1.amazonaws.com Priority: 10 ``` -------------------------------- ### DNS SPF Record Example Source: https://docs.inbound.new/api-reference/domains/get-dns-records Example of an SPF (Sender Policy Framework) TXT DNS record, used for email authentication to specify authorized mail servers. It helps prevent email spoofing. ```dns Name: example.com Value: v=spf1 include:amazonses.com ~all ``` -------------------------------- ### Send, Receive, and List Emails with Inbound Email SDK (JavaScript) Source: https://docs.inbound.new/sdk/quickstart Demonstrates core functionalities of the Inbound Email SDK: sending transactional emails, handling incoming email webhooks, listing recent emails, and retrieving specific email messages by ID. Requires an API key for initialization. ```javascript import { InboundEmailClient } from '@inboundemail/sdk' import type { InboundWebhookPayload } from '@inboundemail/sdk' const inbound = new InboundEmailClient(process.env.INBOUND_API_KEY!) // 1. Send an email export async function sendWelcomeEmail(customerEmail: string) { const { data, error } = await inbound.email.send({ from: 'welcome@yourdomain.com', to: customerEmail, subject: 'Welcome to our service!', html: 'Thanks for signing up. Reply to this email if you have any questions.
', text: 'Welcome! Thanks for signing up. Reply to this email if you have any questions.' }) if (error) { throw new Error(`Failed to send welcome email: ${error}`) } return data } // 2. Handle incoming emails (webhook handler) export async function handleIncomingEmail(payload: InboundWebhookPayload) { const { email } = payload // Get full email details const { data: fullEmail, error } = await inbound.email.received.get(email.id) if (error) { throw new Error(`Failed to get email: ${error}`) } // Auto-categorize and respond based on content if (fullEmail.subject.toLowerCase().includes('support')) { // Support request - auto-reply and route await inbound.email.received.reply({ emailId: email.id, to: fullEmail.from, subject: `Re: ${fullEmail.subject}`, textBody: 'Thank you for contacting support. We will respond within 24 hours.', includeOriginal: false }) // Mark as read since we've handled it await inbound.email.received.markRead(email.id) console.log('Support request processed and auto-replied') } else { // General email - just mark as read await inbound.email.received.markRead(email.id) console.log('General email received and marked as read') } return { success: true } } // 3. List recent emails export async function getRecentEmails() { const { data, error } = await inbound.email.received.list({ limit: 10, timeRange: '24h' }) if (error) { throw new Error(`Failed to get emails: ${error}`) } return data.emails } // 4. Universal email retrieval (works for any email) export async function getAnyEmail(emailId: string) { const { data, error } = await inbound.email.get(emailId) if (error) { throw new Error(`Email not found: ${error}`) } return data } ``` -------------------------------- ### Get Webhook Endpoint using Inbound SDK, cURL, Python, PHP Source: https://docs.inbound.new/api-reference/endpoints/get-endpoint Demonstrates how to fetch details of a specific webhook endpoint. It includes examples using the Inbound SDK for JavaScript, cURL for command-line access, Python with the requests library, and PHP using cURL. These examples show how to make the API request and process the JSON response to display endpoint name, type, and delivery statistics. ```javascript import { InboundEmailClient } from '@inboundemail/sdk' const inbound = new InboundEmailClient(process.env.INBOUND_API_KEY!) const { data: endpoint, error } = await inbound.endpoint.get('ep_abc123') if (error) { console.error('Error fetching endpoint:', error) } else { console.log(`Endpoint: ${endpoint.name} (${endpoint.type}) `) console.log(`Deliveries: ${endpoint.deliveryStats.total} total, ${endpoint.deliveryStats.successful} successful`) } ``` ```bash curl -X GET "https://inbound.new/api/v2/endpoints/ep_abc123" \ -H "Authorization: Bearer your_api_key" ``` ```python import requests response = requests.get( 'https://inbound.new/api/v2/endpoints/ep_abc123', headers={'Authorization': f'Bearer {api_key}'} ) endpoint = response.json() print(f"Endpoint: {endpoint['name']} ({endpoint['type']}) ") print(f"Deliveries: {endpoint['deliveryStats']['total']} total, {endpoint['deliveryStats']['successful']} successful") ``` ```php ``` -------------------------------- ### Initialize Inbound Email Client with API Key Source: https://docs.inbound.new/sdk/quickstart Initializes the InboundEmailClient using an API key stored in environment variables. This client handles authentication and provides a unified interface for email operations. ```javascript import { InboundEmailClient } from '@inboundemail/sdk' const inbound = new InboundEmailClient(process.env.INBOUND_API_KEY!) ```