> ## 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.

# Netlify Functions Quickstart

> Learn how to send emails with SendPost in Netlify Serverless Functions using JavaScript and TypeScript

## Prerequisites

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

* [**Create a SendPost Account**](https://app.sendpost.io/register)
* [**Netlify Account**](https://www.netlify.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. Project Structure

Create a Netlify function:

```
netlify/
  functions/
    send-email.js
```

Or if using TypeScript:

```
netlify/
  functions/
    send-email.ts
```

## 3. Basic Email Function

Create `netlify/functions/send-email.js`:

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

const emailApi = new sendpost.EmailApi();

exports.handler = async (event, context) => {
  // Handle CORS
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
  };

  if (event.httpMethod === 'OPTIONS') {
    return {
      statusCode: 200,
      headers,
      body: '',
    };
  }

  if (event.httpMethod !== 'POST') {
    return {
      statusCode: 405,
      headers,
      body: JSON.stringify({ error: 'Method not allowed' }),
    };
  }

  try {
    const { to, subject, htmlBody, textBody } = JSON.parse(event.body);

    if (!to || !subject || !htmlBody) {
      return {
        statusCode: 400,
        headers,
        body: JSON.stringify({
          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 {
      statusCode: 200,
      headers: {
        ...headers,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        success: true,
        messageId: response.messageId,
      }),
    };
  } catch (error) {
    console.error('SendPost error:', error);
    return {
      statusCode: 500,
      headers: {
        ...headers,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        success: false,
        error: error.message,
      }),
    };
  }
};
```

### TypeScript Version

Create `netlify/functions/send-email.ts`:

```typescript TypeScript theme={null}
import { Handler } from '@netlify/functions';
import sendpost from 'sendpost-js-sdk';

const emailApi = new sendpost.EmailApi();

export const handler: Handler = async (event, context) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
  };

  if (event.httpMethod === 'OPTIONS') {
    return {
      statusCode: 200,
      headers,
      body: '',
    };
  }

  if (event.httpMethod !== 'POST') {
    return {
      statusCode: 405,
      headers,
      body: JSON.stringify({ error: 'Method not allowed' }),
    };
  }

  try {
    const { to, subject, htmlBody, textBody } = JSON.parse(event.body);

    if (!to || !subject || !htmlBody) {
      return {
        statusCode: 400,
        headers,
        body: JSON.stringify({
          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 {
      statusCode: 200,
      headers: {
        ...headers,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        success: true,
        messageId: response.messageId,
      }),
    };
  } catch (error: any) {
    console.error('SendPost error:', error);
    return {
      statusCode: 500,
      headers: {
        ...headers,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        success: false,
        error: error.message,
      }),
    };
  }
};
```

## 4. Environment Variables

Create `netlify.toml`:

```toml theme={null}
[build]
  functions = "netlify/functions"

[build.environment]
  SENDPOST_API_KEY = "your_sub_account_api_key"
```

Or set in Netlify Dashboard:

1. Go to Site settings → Environment variables
2. Add `SENDPOST_API_KEY`

## 5. Common Use Cases

### Welcome Email Function

Create `netlify/functions/welcome-email.js`:

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

const emailApi = new sendpost.EmailApi();

exports.handler = async (event, context) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
  };

  if (event.httpMethod === 'OPTIONS') {
    return { statusCode: 200, headers, body: '' };
  }

  try {
    const { email, firstName } = JSON.parse(event.body);

    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><a href="{{unsubscribe}}">Unsubscribe</a></p>
    `;
    emailMessage.groups = ['welcome'];

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

    return {
      statusCode: 200,
      headers: { ...headers, 'Content-Type': 'application/json' },
      body: JSON.stringify({
        success: true,
        messageId: response.messageId,
      }),
    };
  } catch (error) {
    return {
      statusCode: 500,
      headers: { ...headers, 'Content-Type': 'application/json' },
      body: JSON.stringify({ success: false, error: error.message }),
    };
  }
};
```

## 6. Testing Locally

Install Netlify CLI:

```bash theme={null}
npm install -g netlify-cli
```

Run locally:

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

Test your function:

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

## 7. Deploy

Deploy to Netlify:

```bash theme={null}
netlify deploy --prod
```

Or connect your Git 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="Netlify Functions" icon="netlify" href="https://docs.netlify.com/functions/overview/">
    Learn more about Netlify 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-netlify-functions-example">
    View a complete working example on GitHub
  </Card>
</Columns>
