SDK Quickstart

Get started with the Inbound Email SDK in under 5 minutes. This guide will walk you through installation, authentication, sending your first email, and setting up basic email receiving.
This quickstart uses the unified email API structure with inbound.email.* methods for the best developer experience.

Prerequisites

Before you begin, make sure you have:

Step 1: Install the SDK

1

Install the package

Install the official Inbound Email SDK:
npm install @inboundemail/sdk
The SDK is now installed and ready to use.
2

Set up environment variables

Create a .env file in your project root:
.env
INBOUND_API_KEY=your_api_key_here
Never commit API keys to version control. Always use environment variables.

Step 2: Send Your First Email

1

Create the client

Import and initialize the Inbound client:
import { InboundEmailClient } from '@inboundemail/sdk'

const inbound = new InboundEmailClient(process.env.INBOUND_API_KEY!)
The client automatically handles authentication and provides a unified interface for all email operations.
2

Send an email

Send your first email using the unified API:
const { data, error } = await inbound.email.send({
  from: 'hello@yourdomain.com',
  to: 'recipient@example.com',
  subject: 'Welcome to Inbound!',
  html: '<h1>Hello from Inbound!</h1><p>Your first email sent successfully.</p>',
  text: 'Hello from Inbound! Your first email sent successfully.'
})

if (error) {
  console.error('Failed to send email:', error)
} else {
  console.log('Email sent successfully!')
  console.log('Email ID:', data.id)
}
If successful, you’ll see the email ID logged to your console.
You can use agent@inbnd.dev as the sender for testing without domain verification.

Step 3: Set Up Email Receiving

1

Add your domain

Add a domain to receive emails:
// Create a domain for receiving emails
const { data: domain, error: domainError } = await inbound.domain.create({
  domain: 'yourdomain.com'
})

if (domainError) {
  console.error('Failed to add domain:', domainError)
} else {
  console.log('Domain added:', domain.domain)
  console.log('DNS records to add:', domain.dnsRecords)
}
You’ll need to add the returned DNS records to your domain’s DNS configuration.
2

Create a webhook endpoint

Set up a webhook to receive email notifications:
// Create a webhook endpoint
const { data: endpoint, error: endpointError } = await inbound.endpoint.create({
  name: 'My Webhook',
  type: 'webhook',
  config: {
    url: 'https://api.yourapp.com/webhook',
    timeout: 30,
    retryAttempts: 3
  }
})

if (endpointError) {
  console.error('Failed to create endpoint:', endpointError)
} else {
  console.log('Webhook created:', endpoint.id)
}
Your webhook endpoint is now ready to receive email notifications.
3

Create an email address

Configure an email address to route emails:
// Create an email address that routes to your webhook
const { data: emailAddr, error: addrError } = await inbound.email.address.create({
  address: 'hello@yourdomain.com',
  domainId: domain.id,
  endpointId: endpoint.id
})

if (addrError) {
  console.error('Failed to create email address:', addrError)
} else {
  console.log('Email address created:', emailAddr.address)
}
Emails sent to this address will now be forwarded to your webhook.

Step 4: Handle Incoming Emails

Create a webhook handler to process incoming emails:
app/api/webhook/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { InboundEmailClient } from '@inboundemail/sdk'
import type { InboundWebhookPayload } from '@inboundemail/sdk'

const inbound = new InboundEmailClient(process.env.INBOUND_API_KEY!)

export async function POST(request: NextRequest) {
  try {
    const payload: InboundWebhookPayload = await request.json()
    const { email } = payload

    // Get full email details
    const { data: fullEmail, error } = await inbound.email.received.get(email.id)
    
    if (error) {
      console.error('Failed to get email:', error)
      return NextResponse.json({ error: 'Processing failed' }, { status: 500 })
    }

    // Process the email based on content
    if (fullEmail.subject.toLowerCase().includes('support')) {
      // Auto-reply to support requests
      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.'
      })
      
      // Mark as read
      await inbound.email.received.markRead(email.id)
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Webhook error:', error)
    return NextResponse.json(
      { error: 'Processing failed' }, 
      { status: 500 }
    )
  }
}

Complete Example

Here’s a complete example that demonstrates both sending and receiving emails:
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: `
      <h1>Welcome!</h1>
      <p>Thanks for signing up. Reply to this email if you have any questions.</p>
    `,
    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
}

Key Concepts

Universal Email Management

The SDK provides a unified interface for managing all emails:
// Universal method - works for any email ID
const email = await inbound.email.get(emailId)

// Specific methods for better type safety
const receivedEmail = await inbound.email.received.get(emailId)  // Inbound emails
const sentEmail = await inbound.email.sent.get(emailId)          // Outbound emails
Use inbound.email.get(id) when you’re not sure if an email ID refers to a received or sent email - it automatically detects the type.

Response Pattern

All SDK methods use a consistent { data, error } response pattern:
const { data, error } = await inbound.email.send(params)

if (error) {
  // Handle error
  console.error('Operation failed:', error)
} else {
  // Use data
  console.log('Operation successful:', data)
}

React Email Support

The SDK supports React components for email content:
import { WelcomeEmail } from './email-templates'

const { data, error } = await inbound.email.send({
  from: 'app@yourdomain.com',
  to: 'user@example.com',
  subject: 'Welcome!',
  react: <WelcomeEmail name="John" />  // React component
})

Common Operations

Managing Received Emails

// List recent emails
const { data } = await inbound.email.received.list({
  limit: 20,
  timeRange: '7d'
})

// Get email details  
const { data: email } = await inbound.email.received.get('email_123')

// Reply to an email
const { data: reply } = await inbound.email.received.reply({
  emailId: 'email_123',
  to: 'customer@example.com',
  subject: 'Re: Your question',
  textBody: 'Thanks for your email. Here is my response...'
})

// Mark as read/archived
await inbound.email.received.markRead('email_123')
await inbound.email.received.archive('email_123')

Scheduling Emails

// Schedule with natural language
const { data } = await inbound.email.send({
  from: 'reminders@yourdomain.com',
  to: 'user@example.com',
  subject: 'Scheduled Reminder',
  text: 'This is your scheduled reminder!',
  scheduled_at: 'tomorrow at 9am',
  timezone: 'America/New_York'
})

// Manage scheduled emails
const { data: scheduled } = await inbound.email.sent.listScheduled()
await inbound.email.sent.cancel('scheduled_email_id')

Working with Attachments

import fs from 'fs'

// Send email with attachments
const fileContent = fs.readFileSync('invoice.pdf')
const base64Content = fileContent.toString('base64')

const { data } = await inbound.email.send({
  from: 'billing@yourdomain.com',
  to: 'customer@example.com',
  subject: 'Invoice Attached',
  text: 'Please find your invoice attached.',
  attachments: [{
    content: base64Content,
    filename: 'invoice.pdf',
    contentType: 'application/pdf'
  }]
})

Error Handling Best Practices

try {
  const { data, error } = await inbound.email.send(params)
  
  if (error) {
    // SDK-level error (network, validation, etc.)
    console.error('SDK Error:', error)
    return
  }
  
  console.log('Email sent:', data.id)
} catch (exception) {
  // Unexpected errors
  console.error('Unexpected error:', exception)
}

Next Steps

Quick Reference

Common Methods

Migration Note: If you’re using deprecated mail.* methods, check the Migration Guide for updating to the unified email API.

Need Help?