> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sendpost.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Vercel Functions Quickstart

> Learn how to send emails with SendPost in Vercel Serverless Functions using API routes and edge functions

## Prerequisites

To get the most out of this guide, you'll need to:

* [**Create a SendPost Account**](https://app.sendpost.io/register)
* [**Vercel Account**](https://vercel.com/) (free tier works)
* A **Sub-Account API Key** from your SendPost dashboard

<Info>
  You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails.
</Info>

## 1. Install Dependencies

```shellscript npm theme={null}
npm install sendpost-js-sdk
```

## 2. Environment Setup

Add environment variables in Vercel Dashboard or `vercel.json`:

```json JSON theme={null}
{
  "env": {
    "SENDPOST_API_KEY": "your_sub_account_api_key"
  }
}
```

Or use Vercel CLI:

```bash theme={null}
vercel env add SENDPOST_API_KEY
```

## 3. Serverless Function (API Route)

### Basic Email Function

Create `api/send-email.js`:

```javascript JavaScript theme={null}
const sendpost = require('sendpost-js-sdk');

const emailApi = new sendpost.EmailApi();

module.exports = async (req, res) => {
  // Enable CORS
  res.setHeader('Access-Control-Allow-Credentials', true);
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT');
  res.setHeader('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');

  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }

  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { to, subject, htmlBody, textBody } = req.body;

    if (!to || !subject || !htmlBody) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: to, subject, htmlBody'
      });
    }

    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{ email: to }];
    emailMessage.subject = subject;
    emailMessage.htmlBody = htmlBody;
    emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, '');
    emailMessage.trackOpens = true;
    emailMessage.trackClicks = true;

    const response = await emailApi.sendEmail(
      process.env.SENDPOST_API_KEY,
      { emailMessage }
    );

    return res.status(200).json({
      success: true,
      messageId: response.messageId
    });
  } catch (error) {
    console.error('SendPost error:', error);
    return res.status(500).json({
      success: false,
      error: error.message
    });
  }
};
```

### TypeScript Version

Create `api/send-email.ts`:

```typescript TypeScript theme={null}
import type { VercelRequest, VercelResponse } from '@vercel/node';
import sendpost from 'sendpost-js-sdk';

const emailApi = new sendpost.EmailApi();

export default async function handler(
  req: VercelRequest,
  res: VercelResponse
) {
  // Enable CORS
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT');
  res.setHeader('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');

  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }

  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { to, subject, htmlBody, textBody } = req.body;

    if (!to || !subject || !htmlBody) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: to, subject, htmlBody'
      });
    }

    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{ email: to }];
    emailMessage.subject = subject;
    emailMessage.htmlBody = htmlBody;
    emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, '');
    emailMessage.trackOpens = true;
    emailMessage.trackClicks = true;

    const response = await emailApi.sendEmail(
      process.env.SENDPOST_API_KEY!,
      { emailMessage }
    );

    return res.status(200).json({
      success: true,
      messageId: response.messageId
    });
  } catch (error: any) {
    console.error('SendPost error:', error);
    return res.status(500).json({
      success: false,
      error: error.message
    });
  }
}
```

## 4. Common Use Cases

### Welcome Email Function

Create `api/welcome-email.js`:

```javascript JavaScript theme={null}
const sendpost = require('sendpost-js-sdk');

const emailApi = new sendpost.EmailApi();

module.exports = async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { email, firstName } = req.body;

    if (!email || !firstName) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: email, firstName'
      });
    }

    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{
      email,
      name: firstName,
      customFields: { firstName }
    }];
    emailMessage.subject = 'Welcome {{firstName}}!';
    emailMessage.htmlBody = `
      <h1>Welcome, {{firstName}}!</h1>
      <p>Thank you for joining us. We're excited to have you on board.</p>
      <p>Get started by exploring our features:</p>
      <ul>
        <li>Feature 1</li>
        <li>Feature 2</li>
        <li>Feature 3</li>
      </ul>
      <p>If you have any questions, just reply to this email.</p>
      <p><a href="{{unsubscribe}}">Unsubscribe</a></p>
    `;
    emailMessage.textBody = `
      Welcome, {{firstName}}!
      
      Thank you for joining us. We're excited to have you on board.
      
      Get started by exploring our features:
      - Feature 1
      - Feature 2
      - Feature 3
      
      If you have any questions, just reply to this email.
      
      Unsubscribe: {{unsubscribe}}
    `;
    emailMessage.groups = ['welcome'];
    emailMessage.trackOpens = true;
    emailMessage.trackClicks = true;

    const response = await emailApi.sendEmail(
      process.env.SENDPOST_API_KEY,
      { emailMessage }
    );

    return res.status(200).json({
      success: true,
      messageId: response.messageId
    });
  } catch (error) {
    console.error('SendPost error:', error);
    return res.status(500).json({
      success: false,
      error: error.message
    });
  }
};
```

### Password Reset Email

Create `api/password-reset.js`:

```javascript JavaScript theme={null}
const sendpost = require('sendpost-js-sdk');

const emailApi = new sendpost.EmailApi();

module.exports = async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { email, resetToken, firstName } = req.body;
    const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://yourapp.com';
    const resetUrl = `${appUrl}/reset-password?token=${resetToken}`;

    const emailMessage = new sendpost.EmailMessage();
    emailMessage.from = {
      email: 'hello@playwithsendpost.io',
      name: 'SendPost'
    };
    emailMessage.to = [{
      email,
      name: firstName || 'User',
      customFields: {
        firstName: firstName || 'User',
        resetUrl
      }
    }];
    emailMessage.subject = 'Reset Your Password';
    emailMessage.htmlBody = `
      <h2>Hello {{firstName}},</h2>
      <p>We received a request to reset your password. Click the button below:</p>
      <p>
        <a href="{{resetUrl}}" style="background-color: #5750EC; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block;">
          Reset Password
        </a>
      </p>
      <p>Or copy and paste this link: {{resetUrl}}</p>
      <p>This link will expire in 1 hour.</p>
      <p>If you didn't request this, please ignore this email.</p>
    `;
    emailMessage.groups = ['password-reset'];
    emailMessage.trackClicks = true;

    const response = await emailApi.sendEmail(
      process.env.SENDPOST_API_KEY,
      { emailMessage }
    );

    return res.status(200).json({
      success: true,
      messageId: response.messageId
    });
  } catch (error) {
    console.error('SendPost error:', error);
    return res.status(500).json({
      success: false,
      error: error.message
    });
  }
};
```

## 5. Using with Next.js

If you're using Next.js on Vercel, you can use the same API routes:

Create `pages/api/send-email.js` or `app/api/send-email/route.js`:

```javascript JavaScript theme={null}
import sendpost from 'sendpost-js-sdk';

const emailApi = new sendpost.EmailApi();

export default async function handler(req, res) {
  // Same implementation as above
}
```

## 6. Testing Locally

Install Vercel CLI:

```bash theme={null}
npm i -g vercel
```

Run locally:

```bash theme={null}
vercel dev
```

Test your function:

```bash theme={null}
curl -X POST http://localhost:3000/api/send-email \
  -H "Content-Type: application/json" \
  -d '{
    "to": "user@example.com",
    "subject": "Test Email",
    "htmlBody": "<h1>Hello from Vercel!</h1>"
  }'
```

## 7. Deploy

Deploy to Vercel:

```bash theme={null}
vercel
```

Or connect your GitHub repository for automatic deployments.

<Warning>
  Make sure your sender email domain is verified in your SendPost account before sending emails.
</Warning>

## 8. Next Steps

Explore more examples and use cases:

<Columns cols={3}>
  <Card title="Vercel Documentation" icon="vercel" href="https://vercel.com/docs">
    Learn more about Vercel Functions
  </Card>

  <Card title="SendPost JavaScript SDK" icon="npm" href="https://www.npmjs.com/package/sendpost-js-sdk">
    View the official SDK package on npm
  </Card>

  <Card title="Quickstart Example" icon="github" href="https://github.com/sendpost/sendpost-vercel-functions-example">
    View a complete working example on GitHub
  </Card>
</Columns>
