# Messaging: push and email to your users
Source: https://sovaria.in/docs/messaging

One API for push and email to your app users: templates with variables, audiences written in SQL, a preview before every send, marketing opt-outs with one-click unsubscribe, and a delivery log.

Messaging sends a **template** to an **audience** over **push** (your FCM / APNs credentials, see [Push notifications](https://sovaria.in/docs/mobile-push)) and/or **email** (Sovaria's sender or your own SMTP). Every recipient gets their own copy with their own variables, and every send leaves a per-recipient log.

(Diagram: From a query to every user's phone and inbox)

## Templates

A template has push content (`title`, `body`, `image`, `data`), email content (`subject`, `html`, `text`) or both, with `{{ variables }}` anywhere. **Transactional** templates (receipts, security alerts) always go out; **marketing** templates skip users who opted out and add an unsubscribe link and the one-click `List-Unsubscribe` header (RFC 8058) to every email.

JavaScript:
```ts
await sov.api.messaging.putTemplate({
  name: 'weekly-digest',
  category: 'marketing',
  push: { title: 'Hi {{ first_name }}', body: 'Your week on the {{ plan }} plan' },
  email: { subject: 'Your week, {{ first_name }}', html: '<p>Hello {{ first_name }} …</p>', text: 'Hello {{ first_name }} …' },
})
```

CLI:
```bash
sov messaging template-save weekly-digest --category marketing \
  --push-title "Hi {{ first_name }}" --push-body "Your week on {{ plan }}" \
  --email-subject "Your week, {{ first_name }}" --email-html @digest.html
```

## Audiences in SQL

An audience is a query on your project database that returns `user_id` (your app users' ids). **Every other column becomes a variable** for that user, so the data that picks the audience also personalises the message. Queries run read-only, as one statement, with a 10-second timeout; ids that aren't app users of the project are left out. Functions and tables that reach outside the read-only query are refused (`dblink`, foreign tables, server file and large-object functions), checked both in the text and in the query plan.

SQL:
```sql
select p.user_id, p.first_name, p.plan, count(o.id) as orders
  from profiles p left join orders o on o.user_id = p.user_id
 where p.plan = 'pro' and p.last_seen_at > now() - interval '30 days'
 group by 1, 2, 3
```

JavaScript:
```ts
await sov.api.messaging.putAudience({ name: 'active-pro', sql })
const { users, columns, sample } = await sov.api.messaging.previewAudience({ name: 'active-pro' })
```

## Preview, then send

JavaScript:
```ts
const preview = await sov.api.messaging.send({
  template: 'weekly-digest',
  to: { audience: 'active-pro' },          // or user_ids, sql, topic, all_users
  variables: { promo: '20% off' },         // the same for everyone
  dryRun: true,
})
// preview.counts → { push: { eligible: 980, no_device: 250, opted_out: 10 }, email: { eligible: 1190, … } }
// preview.preview → the first recipient's rendered push and email

const send = await sov.api.messaging.send({ template: 'weekly-digest', to: { audience: 'active-pro' }, variables: { promo: '20% off' } })
const done = await sov.api.messaging.getSend({ sendId: send.id })   // status: sending → done
```

CLI:
```bash
sov messaging send --template weekly-digest --audience active-pro --var promo="20% off"   # previews, then asks
sov messaging status <send-id> --failures
```

- A send answers at once (`status: queued`) and runs as a **durable job**: any Sovaria server can pick it up, it survives restarts and deploys, and it continues from the recipients not yet done (a crash mid-batch can repeat at most that batch of 100, never skip the rest). History in the console (or `getSend`) shows the progress; cancel it any time before it finishes.
- Recipients are found when the send runs, streamed from your database 5,000 at a time, so even a send to millions never holds the list in memory.
- Each recipient and channel is logged as `sent`, `failed` (with an error code such as `UNREGISTERED`, `SEND_ERROR`, `PLAN_LIMIT`), `no_device`, `no_email` or `opted_out` — never the content.
- Push goes to every device the user registered; a user counts as reached when any device accepts it.
- Email through Sovaria's sender is paced at your plan's emails per second instead of failing; your own SMTP (Authentication › Email) isn't counted against `email.sends_month`.
- Sends from functions use the service role key; app users and the anon key can never send.

## Schedule, and send at each user's local time

JavaScript:
```ts
// At one moment
await sov.api.messaging.send({ template: 'weekly-digest', to: { audience: 'active-pro' }, sendAt: '2026-11-02T03:30:00Z' })

// At 09:00 in every recipient's own time zone (the audience's timezone column, e.g. 'Asia/Kolkata')
await sov.api.messaging.send({
  template: 'weekly-digest', to: { audience: 'active-pro' },
  sendAt: '2026-11-02T09:00:00', timezone: 'user', timezoneFallback: 'Asia/Kolkata',
})
await sov.api.messaging.cancelSend({ sendId })   // while it is scheduled or running
```

CLI:
```bash
sov messaging send --template weekly-digest --audience active-pro --at 2026-11-02T09:00:00 --local-time --timezone-fallback Asia/Kolkata
sov messaging cancel <send-id>
```

- A scheduled send waits as **Scheduled** in History; its audience is read when it runs, so users who joined in between are included.
- With local time, add a `timezone` (or `tz`) column with IANA names to the audience; users without one get `timezone_fallback` (else UTC). The send starts when the first time zone reaches the hour and delivers each user at their own 09:00, in waves.
- How many sends may wait at once is `msg.scheduled_sends`; local-time delivery is `msg.timezone_delivery`.

## Opens and clicks

- **Push**: every messaging push carries `sov_send` in its data. When the user opens it, report it from the app: `await sov.inApp.trackOpen(notification.data)` (JavaScript), `try await sovaria.push.trackOpened(userInfo)` (Swift), `sovaria.push.trackOpened(data)` (Kotlin, Dart). Other notifications are ignored, and only a user the send reached can record it.
- **Email**: send with `track: true` (console: *Count email opens and clicks*; CLI `--track`). Links go through a signed redirect on your project URL (only to the link that was in the email) and a 1×1 image counts opens. Mail apps that preload images (Apple Mail Privacy Protection) count every message as opened, so email opens are an estimate; clicks are exact.
- History shows unique opens and clicks per channel next to each send; `getSend` returns them as `engagement`.

## In-app messages

Welcome tours, upgrade prompts and announcements shown inside your app. You define the content (title, body, image, up to two buttons, a banner / modal / card layout), when it shows (`app_open`, `screen:<name>`, `event:<name>`), who sees it (everyone, user ids, or devices on a push topic), a start and end, and how many times one user sees it. The app asks what to show and draws it in its own style, so it matches your design.

JavaScript:
```ts
const [msg] = await sov.inApp.fetch('app_open')        // or 'screen:cart', 'event:purchase'
if (msg) {
  showBanner(msg.content)                                // { title, body, image, layout, buttons }
  await sov.inApp.impression(msg.id)
}
// a button: await sov.inApp.click(msg.id)   ·   closed: await sov.inApp.dismiss(msg.id)
```

Swift:
```swift
if let msg = try await sovaria.inApp.fetch("app_open").first {
    show(msg)                                            // title, body, image, layout, buttons, data
    try await sovaria.inApp.impression(msg.id)
}
```

Kotlin:
```kotlin
sovaria.inApp.fetch("screen:cart").firstOrNull()?.let { msg ->
    show(msg); sovaria.inApp.impression(msg.id)          // click(id), dismiss(id)
}
```

Dart:
```dart
final msgs = await sovaria.inApp.fetch('event:purchase');
if (msgs.isNotEmpty) { show(msgs.first); await sovaria.inApp.impression(msgs.first.id); }
```

CLI:
```bash
sov messaging in-app-save welcome --title "Welcome!" --body "Take the tour" --layout modal --button "Start=/tour"
sov messaging in-app            # users reached, impressions, clicks, dismissals
```

A dismissed message never shows again to that user; one seen its maximum number of times stops too. Messaging › **In-app** lists them with users reached, clicks and dismissals. Active messages per project: `msg.in_app_messages`.

## Opt-outs and unsubscribe

JavaScript (in your app):
```ts
// The signed-in user's own marketing choices
await sov.api.messaging.setPreferences({ marketing: { email: false } })
const { marketing } = await sov.api.messaging.getPreferences()   // { push: true, email: false }
```

Marketing emails carry a signed unsubscribe link that works without signing in (a button on a small page, so mail scanners opening the link don't unsubscribe anyone) and the one-click header mail apps show as "Unsubscribe". Your own settings screen can record choices with `setUserOptout`.

## Limits

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Message templates per project | 10 | 100 | 300 | 1,000 | 5,000 |
| Message audiences per project | 3 | 50 | 200 | 500 | 2,000 |
| Recipients per message send | 1,000 | 50,000 | 200,000 | 1,000,000 | 5,000,000 |
| Message delivery log history | 7 days | 30 days | 90 days | 180 days | 365 days |
| Scheduled message sends waiting per project | 5 | 100 | 500 | 1,000 | 5,000 |
| Delivering a send at each user's local time | — | ✓ | ✓ | ✓ | ✓ |
| Active in-app messages per project | 3 | 50 | 200 | 500 | 2,000 |
| Monthly push notifications | 5,000 | 100,000 | 500,000 | 5,000,000 | 100,000,000 |
| Monthly emails from Sovaria's sender (own SMTP is unlimited) | 100 | 1,000 | 5,000 | 20,000 | 150,000 |
