diff --git a/README.md b/README.md index a15a939..5c81ee1 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/package.json b/package.json index 205fe4d..fd93f0c 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/client.ts b/src/client.ts index 61deea2..2979568 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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`. */ diff --git a/src/emails.ts b/src/emails.ts index 56fe477..17abe5c 100644 --- a/src/emails.ts +++ b/src/emails.ts @@ -9,11 +9,27 @@ import { type HttpConfig, request } from "./http"; */ export type EmailType = "transactional" | "marketing"; -export type EmailMessage = { - /** `Name
` 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
` 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. */ @@ -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 @@ -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`. diff --git a/src/http.ts b/src/http.ts index a81e9df..aa7980f 100644 --- a/src/http.ts +++ b/src/http.ts @@ -64,9 +64,12 @@ export async function request( async function once(config: HttpConfig, init: RequestInit): Promise { 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}`, diff --git a/src/index.ts b/src/index.ts index 3779ce7..b2fd548 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,12 +7,14 @@ export type { } from "./contacts"; export type { EmailMessage, + EmailSender, EmailSendError, EmailType, SendBatchParams, SendBatchResult, SendEmailParams, SendEmailResult, + SenderEmail, RequestOptions, } from "./emails"; export { diff --git a/test/emails.test.ts b/test/emails.test.ts index 6a6a02d..dbc085d 100644 --- a/test/emails.test.ts +++ b/test/emails.test.ts @@ -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( @@ -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: "notifications@offdesk.dev", + 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); +});