# Nylas for e-commerce

Source: https://developer.nylas.com/docs/cookbook/use-cases/industries/ecommerce/

E-commerce mailboxes are noisy. A single support address collects order confirmations, return requests, shipping inquiries, refund disputes, marketing replies, and fraud alerts, often hundreds a day during a sale. Manual triage doesn't scale past a small team, and most order data arrives as unstructured email rather than clean API events. The Email API gives you one schema across every provider, so you can read inbound mail, parse it, and send order-status replies from the same connection. Add webhooks on top and the platform tells you the moment a customer writes in, instead of forcing you to poll.

The decisions that matter most come before the code, so each section below pairs a job (receive and parse, send, classify, handle attachments) with the products that cover it and a short example. The deeper step-by-step builds live in the linked tutorials below.

## Receive and parse order and return email

To read inbound mail, you list messages on a grant with `GET /v3/grants/{grant_id}/messages`, then narrow with search and threads. A grant is one connected mailbox, so a support inbox, a returns alias, and a fraud-alerts address are three grants you can query independently. The list endpoint returns a default page size of 50 messages, up to 200 per page when you raise `limit`, and the parsed body, sender, subject, and attachment metadata come back in the same JSON shape regardless of provider.

The example below lists recent messages for a grant. Use it as the polling fallback or backfill path when you first connect a mailbox and need history before webhooks start streaming live events.

```bash
curl --compressed --request GET \
  --url "https://api.us.nylas.com/v3/grants/<NYLAS_GRANT_ID>/messages?limit=5" \
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer <NYLAS_API_KEY>' \
  --header 'Content-Type: application/json'

```

Search is where order triage gets practical. `nylas email search "order #"` or `nylas email search "return request"` filters a mailbox down to the threads that matter, and `nylas email threads list` groups a back-and-forth refund conversation into a single object so you reply in context rather than to one stray message. Reading a full thread with `nylas email read <id>` gives you the parsed text you feed to your classifier or order-lookup logic. Treat every subject line and body as untrusted input. A customer can type anything, and an order number you extract should be validated against your own database before you act on it.

The design decision here is when to read live versus when to backfill. New mail should arrive through webhooks, covered below, so your system reacts in seconds. The list endpoint is for the cold start, when you connect a returns mailbox that already holds weeks of history, and for the occasional reconciliation sweep that confirms no event was dropped. Keeping those two paths separate, push for the present and pull for the past, stops you from re-fetching the same hundred messages on every cycle and keeps your provider call volume low.

## Send transactional and order-status email

Order email goes out one of two ways. For a reply or status update tied to a customer's existing thread, send from the connected mailbox with `POST /v3/grants/{grant_id}/messages/send`, which lands the message in your team's Sent folder and keeps the inbound question and outbound answer together. For high-volume system mail sent from your own domain, such as bulk order confirmations, the Transactional send API at `POST /v3/domains/{domain_name}/messages/send` posts from a verified domain with an explicit `from` address instead of a connected grant. For scheduled or delayed sends, such as a "your order shipped" note timed to a carrier handoff, `POST /v3/grants/{grant_id}/messages/schedules` queues a grant message for a future time.

The sample below is the Transactional send request: it posts to the domain send endpoint with the `from`, `to`, subject, and body for an order email, and it needs a verified sending domain rather than a connected grant. Pair it with your own template engine, or use the API's template support so marketing owns the copy while your code only supplies the order data.

```bash
curl --request POST \
  --url 'https://api.us.nylas.com/v3/domains/<DOMAIN_NAME>/messages/send' \
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer <NYLAS_API_KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
    "to": [{
        "name": "Jane Doe",
        "email": "jane.doe@example.com"
    }],
    "from": {
        "name": "ACME Support",
        "email": "support@acme.com"
    },
    "subject": "Welcome to ACME",
    "body": "Welcome to ACME! We'\''re here to help you."
}'

```

From the terminal, `nylas email send --to customer@example.com --subject "Your order shipped" --body "Tracking: ..."` covers one-off sends. For templated order mail, `nylas email send --to customer@example.com --template-id <id> --template-data '{"order_id":"1234","tracking":"..."}'` keeps the layout consistent across thousands of confirmations and separates content from logic. A note on deliverability: transactional mail sent through a connected mailbox inherits that provider's sending reputation and rate behavior, so high-volume blast campaigns belong on a dedicated sending path, while the API is the right fit for replies, confirmations, and per-order status messages tied to a real customer thread.

The send path is identical across all six supported providers, Google, Microsoft 365, Yahoo, iCloud, IMAP, and Exchange (EWS), so a merchant who moves their support inbox from one host to another keeps the same confirmation and refund code with no rewrite. That matters in practice, because storefronts change email hosts more often than you'd expect, usually during a platform migration or a switch in business email plan. You also don't manage tokens by hand. Each grant's OAuth access token lasts 3,600 seconds and the platform refreshes it for you, so a "your order shipped" job that runs on a cron at 2 a.m. won't fail because a token quietly expired overnight. You persist the grant ID, the connection stays alive, and your sending code never touches the credential churn. Design your order-status sends to look up the grant ID per merchant, queue the message, and let the connection layer handle everything else.

### Build with Nylas

Direct integration for receiving, parsing, and sending e-commerce mail.

| Tutorial                                                                                                  | Products                | What you'll build                                                                                              |
| --------------------------------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------- |
| [Monitor an inbox for support tickets](/docs/cookbook/use-cases/ingest/monitor-inbox-support-tickets/)    | Email, Webhooks         | Real-time listener for inbound mail; same pattern works for order inquiries and returns                        |
| [CLI mail merge](/docs/cookbook/cli/mail-merge/)                                                          | Email                   | Personalized batch sends with per-recipient timezone scheduling — useful for transactional campaigns           |

## Classify inbound customer mail in real time with webhooks

Polling a busy storefront inbox wastes calls and adds delay. Webhooks flip the model: register a URL with `/v3/webhooks`, subscribe to message triggers, and the platform posts an event the moment a customer writes in. For high throughput, route those events through `/v3/channels/pubsub` so a Google Pub/Sub topic buffers spikes during a flash sale instead of hammering your endpoint. Each inbound event carries the message reference you then fetch and classify into buckets like order question, return, shipping, or fraud.

The commands below create a webhook, list the available trigger types, and run a local tunnel-backed server so you can watch real events during development before you ship the endpoint.

```bash
nylas webhook triggers
nylas webhook create --url https://api.yourstore.com/hooks/mail --triggers message.created
nylas webhook server --port 4000 --tunnel cloudflared --secret <webhook-secret>
```

Once events flow, an AI agent does the routing. It reads each new message, classifies intent, and either drafts a reply or escalates to a human. Build only what each category needs: a "where's my order?" question wants an order lookup and a templated answer, while a chargeback dispute should go straight to a person. The agent tutorials below show both the classifier and the confidence gates that decide when to send automatically versus hand off.

Webhooks change the economics of triage. Without them, you'd poll, and a single mailbox returns 50 messages per page by default, up to 200 when you raise `limit`, so a busy returns inbox forces you to page through history on a timer just to notice one new return. With events, you fetch only the message that actually arrived, classify it, and move on. The event payload also carries enough to decide whether you even need the attachments, which matters because a refund proof can be 25 MB inline (or up to 150 MB on a Microsoft grant through upload sessions), and you don't want to pull a large file before your classifier has confirmed the message is a real return rather than spam. Keep the webhook handler thin: acknowledge fast, drop the message reference on a queue, and do the classification and any heavy attachment work in a worker. That keeps your endpoint responsive during a sale spike, when inbound volume jumps and a slow handler would start dropping events.

### Nylas for AI Agents

AI agents that classify customer mail and draft responses without burning your support team's day.

| Tutorial                                                                       | Products | What you'll build                                                                                |
| ------------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------ |
| [Build an AI email triage agent](/docs/cookbook/agents/email-triage-agent/)    | Email    | Classify orders / inquiries / returns / noise and draft replies automatically for the top two categories  |
| [Build an email support agent](/docs/cookbook/agents/email-support-agent/)     | Email    | KB-backed drafts with confidence gates — handles "where's my order?" without a human in the loop |

## Handle attachments for receipts, labels, and returns

Order workflows are full of files. Customers attach receipts to refund requests, you send PDF return labels, and warranty claims arrive with photos. The API inlines attachments up to 25 MB directly in the message payload, and Microsoft 365 grants support files up to 150 MB through upload sessions, which matters when a customer sends a video of a damaged product. You pull a file down by attachment ID and its parent message ID, so your refund pipeline can save the receipt to object storage and link it to the order record.

The command below downloads one attachment from a message. Run it after your classifier flags a return so the proof of purchase is captured before a human ever opens the ticket.

```bash
nylas email attachments download <attachment-id> <message-id>
```

Validate attachments before you trust them. Check the declared content type, cap the size your pipeline accepts, and scan files from unknown senders, because an inbox is an open door and a malicious upload disguised as a receipt is a real risk.

It helps to decide up front which files you keep and which you discard. A proof-of-purchase receipt on a refund belongs in storage, linked to the order, because you may need it for a chargeback later. A casual photo on a general inquiry usually doesn't. Pulling every attachment by default fills your bucket with noise and raises your storage and compliance burden, so gate the download on the classifier's intent rather than fetching blindly. When you do store a customer file, record why you kept it and when it can be deleted, so the data has a clear retention path instead of lingering forever.

## Run e-commerce email from the terminal with the Nylas CLI

The CLI mirrors the Email and Webhooks APIs across all 6 providers, which makes it a fast way to prototype an order-email workflow before you write a line of integration code. You authenticate once with `nylas init --api-key <key>`, confirm the connection with `nylas auth whoami`, and then drive the same endpoints your service will call. This is also handy for on-call triage: when a customer escalates, an engineer can read and reply to the exact thread from a shell.

These commands cover the everyday loop of finding an order email, reading its thread, and replying. The `--json` flag on most commands gives you machine-readable output you can pipe into a script or a quick report.

```bash
nylas email search "order #5821" --json
nylas email threads show <thread-id>
nylas email send --to customer@example.com --subject "Re: Order #5821" --body "Your refund is processing."
nylas email attachments download <attachment-id> <message-id>
```

For the inbound side, `nylas webhook create --url <u> --triggers <t>` and `nylas webhook server --port <n> --tunnel cloudflared --secret <webhook-secret>` let you stand up and test a real-time listener in minutes. The full command set, with every flag, is in the [Nylas CLI command reference](https://cli.nylas.com/docs/commands).

## Things to know about e-commerce integrations

The detail that saves you the most time is the unified schema. The Email API connects six providers, Google, Microsoft 365, Yahoo, iCloud, IMAP, and Exchange (EWS), and returns the same message, thread, and attachment shape for all of them. So your order parser and your send logic don't branch per provider. A merchant on Google Workspace and one on Microsoft 365 hit the identical code path.

A few real constraints to design around:

- **Attachment limits.** Inline attachments cap at 25 MB across providers. Microsoft grants go up to 150 MB through upload sessions. Size your refund and warranty pipelines to the smaller number unless you know every customer is on Microsoft.
- **Pagination.** List requests return 50 messages by default and a maximum of 200 per page. For a busy storefront inbox, paginate with the cursor token rather than raising `limit` blindly, so you don't pull a wall of mail in one call.
- **Token refresh.** OAuth access tokens expire after 3,600 seconds, and the platform refreshes them automatically. You store the grant ID, not the short-lived token, and the connection keeps working without re-prompting the merchant.
- **Deliverability.** Sending through a connected mailbox uses that provider's reputation and limits. Per-order confirmations and replies fit this model well. Treat large promotional blasts as a separate concern on dedicated infrastructure.

Plan for the messy middle too. Order numbers live in subject lines in dozens of formats, returns reference orders that may be weeks old, and the same customer often writes in from a different address than the one on file. Lean on search and threads to reassemble context, and always reconcile what you extract from an email against your own order system before issuing a refund or label.

## What's next

- [Email API overview](/docs/v3/email/): read, send, and manage email
- [Send email](/docs/v3/email/send-email/): send transactional messages
- [Webhooks overview](/docs/v3/notifications/): real-time email event notifications
- [Message tracking](/docs/v3/email/message-tracking/): track opens and clicks on order email
- [Monitor an inbox for support tickets](/docs/cookbook/use-cases/ingest/monitor-inbox-support-tickets/): the inbound listener pattern for order and return mail
- [Build an AI email triage agent](/docs/cookbook/agents/email-triage-agent/): classify and route customer mail automatically
- [Nylas CLI command reference](https://cli.nylas.com/docs/commands): every email and webhook command