# Email API quickstart

Send your first email with the OnCharge email API: create an API key, verify your sending domain, send, and check what happened. The email API is part of OnCharge Messaging, which also covers email and SMS marketing; in the dashboard it lives under **Email & SMS**.

> **Early access: the API may change.** OnCharge Messaging is in early access. Endpoints, fields, limits and event names can still change before general availability. To join, [request early access](/email-api#early-access).

## Base URL and authentication

Every endpoint is under the same base URL as the rest of the OnCharge merchant API:

```text
https://app.oncharge.io/api/v1
```

Authenticate with a messaging API key in the `Authorization` header:

```http
Authorization: Bearer oc_msg_live_...
```

| Key | Prefix | What it does |
|---|---|---|
| Live key | `oc_msg_live_` | Sends real email. |
| Test key | `oc_msg_test_` | Runs every check and the whole sending pipeline but never delivers. Its events are simulated, and webhooks carry `livemode: false`. |

Each key has a scope:

| Scope | Can |
|---|---|
| `sending` | Send email only. It can be limited to one domain, which suits a key you put in a store plugin or an SMTP client. |
| `full` | Everything in the email API: emails, domains, templates, inbound email, suppressions and keys. |

The signed store keys you already use for payments (`X-Oncharge-Key`, `X-Oncharge-Timestamp` and `X-Oncharge-Signature`, see [Authentication & signing](https://oncharge.io/docs/authentication)) also work on these endpoints, with `full` scope for that store's account. Use a messaging key when you only need email: it is a single header and can be limited to sending.

Keep keys on your server, never in browser code or a mobile app.

## 1. Create an API key

In the dashboard, open **Email & SMS → API keys** and create a key. The token is shown once: store it as a server-side secret.

```bash title=".env"
ONCHARGE_MESSAGING_KEY=oc_msg_live_...
```

You can also create keys with the API, using a key that has `full` scope:

```bash
curl -X POST https://app.oncharge.io/api/v1/messaging-api-keys \
  -H "Authorization: Bearer $ONCHARGE_MESSAGING_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Store receipts", "scope": "sending" }'
```

Add `"domain_id"` to limit a `sending` key to one of your domains. The response shows the token once. `GET /messaging-api-keys` lists your keys (without their tokens) and `DELETE /messaging-api-keys/{id}` revokes one at once.

## 2. Verify your domain

You send from your own domain, so mail is signed as you and your reputation stays yours. Add the domain, put the records OnCharge gives you in your DNS, and verify:

```bash
curl -X POST https://app.oncharge.io/api/v1/email-domains \
  -H "Authorization: Bearer $ONCHARGE_MESSAGING_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "example.com" }'
```

The response lists the DNS records to add. Every record points at an OnCharge name under `m.oncharge.io`. Once they are in place:

```bash
curl -X POST https://app.oncharge.io/api/v1/email-domains/{id}/verify \
  -H "Authorization: Bearer $ONCHARGE_MESSAGING_KEY"
```

[Domains](https://oncharge.io/docs/messaging/domains) explains each record and the domain statuses.

## 3. Send an email

### cURL

```bash
curl -X POST https://app.oncharge.io/api/v1/emails \
  -H "Authorization: Bearer $ONCHARGE_MESSAGING_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1001-receipt" \
  -d '{
    "from": "Example Store <orders@example.com>",
    "to": ["shopper@example.net"],
    "subject": "Your order #1001 is confirmed",
    "html": "<p>Thanks for your order. We will email you when it ships.</p>",
    "text": "Thanks for your order. We will email you when it ships.",
    "tags": [{ "name": "type", "value": "receipt" }]
  }'
```

```json title="Response 200"
{ "id": "0b6f2c1e-7d4a-4e8b-9f3c-2a1d5e6b7c80" }
```

### Node.js

No SDK needed: any HTTP client works.

```js title="send.mjs"
const res = await fetch('https://app.oncharge.io/api/v1/emails', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.ONCHARGE_MESSAGING_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': 'order-1001-receipt',
  },
  body: JSON.stringify({
    from: 'Example Store <orders@example.com>',
    to: ['shopper@example.net'],
    subject: 'Your order #1001 is confirmed',
    html: '<p>Thanks for your order. We will email you when it ships.</p>',
    tags: [{ name: 'type', value: 'receipt' }],
  }),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.type}: ${body.error.message}`);
console.log(body.id);
```

With the Node SDK (early access, see [SDKs & MCP](https://oncharge.io/docs/messaging/sdks)):

```ts
import { OnCharge } from '@oncharge/node';

const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_MESSAGING_KEY! });

const { id } = await oncharge.emails.send(
  {
    from: 'Example Store <orders@example.com>',
    to: ['shopper@example.net'],
    subject: 'Your order #1001 is confirmed',
    html: '<p>Thanks for your order. We will email you when it ships.</p>',
  },
  { idempotencyKey: 'order-1001-receipt' },
);
```

### PHP

```php title="send.php"
<?php
$payload = json_encode([
    'from' => 'Example Store <orders@example.com>',
    'to' => ['shopper@example.net'],
    'subject' => 'Your order #1001 is confirmed',
    'html' => '<p>Thanks for your order. We will email you when it ships.</p>',
    'tags' => [['name' => 'type', 'value' => 'receipt']],
]);

$ch = curl_init('https://app.oncharge.io/api/v1/emails');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('ONCHARGE_MESSAGING_KEY'),
        'Content-Type: application/json',
        'Idempotency-Key: order-1001-receipt',
    ],
    CURLOPT_POSTFIELDS => $payload,
]);
$body = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($status !== 200) {
    throw new RuntimeException($body['error']['type'] . ': ' . $body['error']['message']);
}
echo $body['id'];
```

Send the same `Idempotency-Key` when you retry: OnCharge returns the first response instead of sending twice. See [Sending email](https://oncharge.io/docs/messaging/sending) for every field, templates, scheduling and batches.

## 4. Check what happened

Fetch the email to see its latest event:

```bash
curl https://app.oncharge.io/api/v1/emails/0b6f2c1e-7d4a-4e8b-9f3c-2a1d5e6b7c80 \
  -H "Authorization: Bearer $ONCHARGE_MESSAGING_KEY"
```

`last_event` moves from `queued` to `sent`, then `delivered` (or `bounced`, `failed` and the others listed in [Sending email](https://oncharge.io/docs/messaging/sending#retrieve-and-list-emails)). Every email stays in the log for 90 days, in the dashboard and through the API.

To hear about events as they happen instead of polling, add a webhook endpoint: [Email webhooks](https://oncharge.io/docs/messaging/webhooks).

## Next steps

- [Sending email](https://oncharge.io/docs/messaging/sending): every field, attachments, templates, scheduling, batches and suppressions.
- [Domains](https://oncharge.io/docs/messaging/domains): the DNS records and how verification works.
- [Email webhooks](https://oncharge.io/docs/messaging/webhooks): delivery, bounce, complaint, open and click events.
- [SMTP relay](https://oncharge.io/docs/messaging/smtp): send from any app or plugin that speaks SMTP.
- [Inbound email](https://oncharge.io/docs/messaging/inbound): receive replies and parse them.
- [Limits & errors](https://oncharge.io/docs/messaging/limits): rate limits, sizes and error types.
- Prices: [Email & SMS pricing](/pricing#messaging).
