Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,22 @@ const { id } = await zalify.emails.send(
- A recipient on your suppression list (an earlier hard bounce or spam complaint) still gets an `id`, but the message is not delivered.
- Each day your workspace can email a limited number of addresses it has never emailed before. New workspaces start at 1,000 a day for transactional mail and 500 for marketing. The limit doubles after each day with low bounce and complaint rates, and goes away once it reaches 50,000. Over the limit, sends fail with `new_recipient_limit` (marketing waits until the next day). People you've emailed before are never limited.

### Send from a sender set up in Zalify

Instead of `from`, pass `senderEmailId`: a sender email from **Settings → Email**. Its name, address and Reply-To are used (your `replyTo` still wins), so they're managed in Zalify rather than in your code.

```ts
const { data: senders } = await zalify.emails.listSenders();
// [{ id, name, email, replyTo, verified }]

await zalify.emails.send(
{ senderEmailId: process.env.ZALIFY_SENDER_EMAIL_ID, to, subject, html },
{ idempotencyKey: `reset:${tokenId}` }
);
```

A message takes `from` or `senderEmailId`, not both. A sender that isn't in your workspace or isn't verified yet fails with `unverified_sender`.

## Send a batch

Send up to 100 messages in one request. A refused message doesn't fail the others.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zalify/sdk",
"version": "0.3.0",
"version": "0.4.0",
"description": "Official Node.js / TypeScript SDK for the Zalify API",
"keywords": ["zalify", "email", "transactional email", "contacts", "sdk"],
"homepage": "https://github.com/zalify/zalify-node#readme",
Expand Down
2 changes: 1 addition & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Emails } from "./emails";
import { Webhooks } from "./webhooks";
import type { HttpConfig } from "./http";

export const VERSION = "0.3.0";
export const VERSION = "0.4.0";

export type ZalifyOptions = {
/** A Zalify Public API key (`zalify_api_…`). Defaults to `ZALIFY_API_KEY`. */
Expand Down
42 changes: 39 additions & 3 deletions src/emails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,27 @@ import { type HttpConfig, request } from "./http";
*/
export type EmailType = "transactional" | "marketing";

export type EmailMessage = {
/** `Name <address>` or a bare address, on a domain verified in Zalify. */
from: string;
/**
* The sender: a `from` address, or `senderEmailId`, a sender email set up in
* Zalify (Settings → Email; list them with `emails.listSenders()`) whose
* name, address and Reply-To are then used.
*/
export type EmailSender =
| {
/** `Name <address>` or a bare address, on a domain verified in Zalify. */
from: string;
senderEmailId?: never;
}
| {
/** A sender email's `id` from `emails.listSenders()`. */
senderEmailId: string;
from?: never;
};

export type EmailMessage = EmailSender & {
/** One recipient. Send one message per recipient. */
to: string;
/** Defaults to the sender email's Reply-To with `senderEmailId`. */
replyTo?: string;
subject: string;
/** Rendered HTML, up to 5 MB. */
Expand All @@ -30,6 +46,18 @@ export type EmailMessage = {

export type SendEmailParams = EmailMessage & { type?: EmailType };

/** A sender email from Settings → Email. */
export type SenderEmail = {
/** Pass as `senderEmailId`. */
id: string;
name: string;
email: string;
/** Where replies go; null when they go to `email`. */
replyTo: string | null;
/** Ready to send from. Sends from an unverified sender fail with `unverified_sender`. */
verified: boolean;
};

export type SendEmailResult = {
/**
* The message id. A recipient on your suppression list (an earlier hard
Expand Down Expand Up @@ -86,6 +114,14 @@ export class Emails {
});
}

/** The sender emails your workspace can send from, for `senderEmailId`. */
async listSenders(): Promise<{ data: SenderEmail[] }> {
return request<{ data: SenderEmail[] }>(this.http, {
method: "GET",
path: "/email/senders",
});
}

/**
* Send up to 100 emails in one request. A refused message doesn't fail the
* others: check each entry of `data` for `id` or `error`.
Expand Down
5 changes: 4 additions & 1 deletion src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ export async function request<T>(
async function once<T>(config: HttpConfig, init: RequestInit): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), config.timeoutMs);
// Called on its own, not as config.fetch(...): Cloudflare Workers reject a fetch
// invoked with any other `this` ("Illegal invocation").
const fetchImpl = config.fetch;
let response: Response;
try {
response = await config.fetch(`${config.baseUrl}${init.path}`, {
response = await fetchImpl(`${config.baseUrl}${init.path}`, {
method: init.method,
headers: {
Authorization: `Bearer ${config.apiKey}`,
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ export type {
} from "./contacts";
export type {
EmailMessage,
EmailSender,
EmailSendError,
EmailType,
SendBatchParams,
SendBatchResult,
SendEmailParams,
SendEmailResult,
SenderEmail,
RequestOptions,
} from "./emails";
export {
Expand Down
36 changes: 36 additions & 0 deletions test/emails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ const client = (fetchImpl: typeof fetch, extra = {}) =>
...extra,
});

test("fetch is called on its own, as Cloudflare Workers require", async () => {
// Workers throw "Illegal invocation" when fetch runs with another `this`
const fetchImpl = function (this: unknown) {
if (this !== undefined && this !== globalThis) throw new TypeError("Illegal invocation");
return Promise.resolve(json({ id: "msg_1" }));
} as unknown as typeof fetch;
assert.deepEqual(await client(fetchImpl).emails.send(message), { id: "msg_1" });
});

test("send posts the message with the key and an idempotency key", async () => {
const { calls, fetchImpl } = scripted([json({ id: "msg_1" })]);
const result = await client(fetchImpl).emails.send(
Expand Down Expand Up @@ -170,3 +179,30 @@ test("a custom baseUrl is used without a trailing slash", async () => {
);
assert.equal(calls[0]?.url, "http://localhost:3000/api/v1/email/send");
});

test("send can name a sender email instead of a from address", async () => {
const { calls, fetchImpl } = scripted([json({ id: "msg_1" })]);
const { from: _from, ...rest } = message;
await client(fetchImpl).emails.send({ ...rest, senderEmailId: "se_1" });
assert.deepEqual(JSON.parse(String(calls[0]?.init.body)), {
...rest,
senderEmailId: "se_1",
});
});

test("listSenders gets the workspace's sender emails", async () => {
const sender = {
id: "se_1",
name: "Offdesk",
email: "[email protected]",
replyTo: null,
verified: true,
};
const { calls, fetchImpl } = scripted([json({ data: [sender] })]);
assert.deepEqual(await client(fetchImpl).emails.listSenders(), {
data: [sender],
});
assert.equal(calls[0]?.url, "https://app.zalify.com/api/v1/email/senders");
assert.equal(calls[0]?.init.method, "GET");
assert.equal(calls[0]?.init.body, undefined);
});
Loading