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 packages/dms-mailing/docs/5.extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,22 @@ await SendTemplate("invoice-sent", {
- A send carries at most 10 files, adding up to at most 10 MiB. Over that, the call rejects with `code` `attachments_too_large` before anything is sent or logged.
- **Mailing › Sends** lists each file's name and size, and keeps its SHA-256, never its bytes. A send with files cannot be sent again from the dashboard: send it again from your code.

### Copy and reply to

`cc` copies addresses on every message of the call, and `replyTo` sets where replies go for this send instead of the workspace's reply-to address:

```typescript fragment
await SendTemplate("invoice-sent", {
tenantId,
to: "sofie@example.com",
cc: ["accounting@example.com"],
replyTo: "billing@example.com",
});
```

- A `cc` address on the suppression list is left out. The send log keeps the copied addresses (`json_cc`).
- There is no `bcc`.

### Amounts and dates

Pass an amount or a date as a value, and the e-mail writes it in the locale of the send.
Expand Down
4 changes: 4 additions & 0 deletions packages/dms-mailing/src/db/tables/sends.table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ export class MailingSend extends Table {
@Field("string")
declare json_attachments?: string;

/** JSON list of the addresses copied on the e-mail; absent for most sends. */
@Field("string")
declare json_cc?: string;

@Field("number")
declare opens: number;

Expand Down
12 changes: 12 additions & 0 deletions packages/dms-mailing/src/services/addresses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { EmailAddress } from "@antelopejs/interface-email";
import { isText } from "../validation/guards";

export const addressOf = (to: EmailAddress): string =>
isText(to) ? to : to.email;

export const nameOf = (to: EmailAddress): string | undefined =>
isText(to) ? undefined : to.name;

export const toRecipients = (
to: EmailAddress | EmailAddress[],
): EmailAddress[] => (Array.isArray(to) ? to : [to]);
22 changes: 15 additions & 7 deletions packages/dms-mailing/src/services/checked-send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
sendTemplate,
} from "./send";
import { suppressionsOf } from "./suppressions";
import { isText } from "../validation/guards";
import { addressOf, toRecipients } from "./addresses";

/**
* A send the module checks against the suppression list. `allowSuppressed`
Expand All @@ -25,11 +25,6 @@ export const SUPPRESSED_ERROR_PREFIX = "$dms_mailing.errors.suppressed.";

const NO_LATENCY = null;

const addressOf = (to: EmailAddress): string => (isText(to) ? to : to.email);

const toRecipients = (to: EmailAddress | EmailAddress[]): EmailAddress[] =>
Array.isArray(to) ? to : [to];

/** The error a suppressed recipient's send keeps: an i18n key per reason. */
export function suppressedError(row: MailingSuppression): string {
return `${SUPPRESSED_ERROR_PREFIX}${row.reason}`;
Expand Down Expand Up @@ -85,15 +80,28 @@ async function sendAllowed(
return result.results ?? [result];
}

/** The send without the copied addresses that are on the suppression list. */
async function withoutSuppressedCc(
params: CheckedSendParams,
): Promise<CheckedSendParams> {
if (!params.cc?.length) return params;
const blocked = await blockedRecipients(params, params.cc);
return {
...params,
cc: params.cc.filter((to) => !blocked.has(normalizeAddress(addressOf(to)))),
};
}

/**
* Sends a template to every recipient but those on the suppression list,
* which are logged as `suppressed` instead. The results keep the order the
* recipients were given in.
*/
export async function sendUnlessSuppressed(
slug: string,
params: CheckedSendParams,
given: CheckedSendParams,
): Promise<SendTemplateResult> {
const params = await withoutSuppressedCc(given);
const recipients = toRecipients(params.to);
const rows = await blockedRecipients(params, recipients);
if (!rows.size) return sendTemplate(slug, params);
Expand Down
18 changes: 8 additions & 10 deletions packages/dms-mailing/src/services/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import {
type VersionedSnapshot,
workingSnapshot,
} from "./templates";
import { isText } from "../validation/guards";
import { addressOf, nameOf, toRecipients } from "./addresses";

export interface PreparedSend {
content: TemplateContent;
Expand All @@ -75,6 +75,8 @@ export interface PreparedSend {
attention: string;
/** The files every recipient gets; absent for most sends. */
attachments?: BufferAttachment[];
cc?: EmailAddress[];
replyTo?: EmailAddress;
}

/**
Expand Down Expand Up @@ -155,14 +157,6 @@ const OUTCOME_SEVERITY: Record<SendStatus, number> = {
failed: 9,
};

const addressOf = (to: EmailAddress): string => (isText(to) ? to : to.email);

const nameOf = (to: EmailAddress): string | undefined =>
isText(to) ? undefined : to.name;

const toRecipients = (to: EmailAddress | EmailAddress[]): EmailAddress[] =>
Array.isArray(to) ? to : [to];

/**
* The content a send renders and the version it belongs to. A real send gets
* what customers receive; a test send gets the draft when there is one, so a
Expand Down Expand Up @@ -285,6 +279,8 @@ export async function prepare(
category: template.category ?? "",
attention: template.attention,
attachments,
cc: params.cc?.length ? params.cc : undefined,
replyTo: params.replyTo,
};
}

Expand All @@ -306,7 +302,8 @@ export function messageFor(
from: settings.senderEmail
? { email: settings.senderEmail, name: settings.senderName || undefined }
: undefined,
replyTo: settings.replyTo || undefined,
replyTo: prepared.replyTo ?? (settings.replyTo || undefined),
cc: prepared.cc,
tags: [MODULE_ID, prepared.slug],
metadata: {
tenantId: prepared.tenantId,
Expand Down Expand Up @@ -460,6 +457,7 @@ async function record(
source: params.source,
json_variables: JSON.stringify(params.variables ?? {}),
json_attachments: attachmentsLog(prepared.attachments),
json_cc: prepared.cc && JSON.stringify(prepared.cc.map(addressOf)),
opens: 0,
clicks: 0,
isTest: Boolean(params.isTest),
Expand Down
71 changes: 71 additions & 0 deletions packages/dms-mailing/src/test/integration/send-cc-reply-to.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { expect } from "chai";
import { DEFAULT_TENANT_ID } from "@antelopejs/interface-dms/constants";
import { GetModel } from "@antelopejs/interface-database-decorators";
import { SendModel } from "../../db";
import { suppressAddress } from "../../services/suppressions";
import { declaration, mailing } from "../helpers/declarations";
import { capturedMail, rawMail } from "../helpers/mail-store";

const stamp = Date.now();
const slug = `cc-reply-to-${stamp}`;
const VARIABLES = { customer: { firstName: "Sofie" } };

const mailTo = (address: string): string =>
capturedMail()
.map(rawMail)
.find((message) => message.includes(address)) ?? "";

describe("[integration] sends with cc and reply-to", () => {
before(async () => {
const { DeclareTemplate } = await mailing();
await DeclareTemplate(declaration(slug));
});

it("copies the address, sets the reply-to and logs the copy", async () => {
const { SendTemplate } = await mailing();
const to = `to-${stamp}@example.test`;
const cc = `boss-${stamp}@example.test`;
const result = await SendTemplate(slug, {
tenantId: DEFAULT_TENANT_ID,
to,
cc: [cc],
replyTo: `replies-${stamp}@example.test`,
variables: VARIABLES,
});

expect(result.status).to.equal("sent");
const raw = mailTo(to);
expect(raw).to.match(new RegExp(`^Cc:.*${cc}`, "im"));
expect(raw).to.match(new RegExp(`^Reply-To:.*replies-${stamp}@`, "im"));
const send = await GetModel(SendModel, DEFAULT_TENANT_ID).get(
result.sendId,
);
expect(JSON.parse(send?.json_cc ?? "null")).to.deep.equal([cc]);
});

it("leaves a suppressed address out of the copies", async () => {
const { SendTemplate } = await mailing();
const to = `to-suppressed-cc-${stamp}@example.test`;
const suppressed = `blocked-${stamp}@example.test`;
const allowed = `allowed-${stamp}@example.test`;
await suppressAddress(DEFAULT_TENANT_ID, {
email: suppressed,
reason: "manual",
});
const result = await SendTemplate(slug, {
tenantId: DEFAULT_TENANT_ID,
to,
cc: [suppressed, allowed],
variables: VARIABLES,
});

expect(result.status).to.equal("sent");
const raw = mailTo(to);
expect(raw).to.contain(allowed);
expect(raw).to.not.contain(suppressed);
const send = await GetModel(SendModel, DEFAULT_TENANT_ID).get(
result.sendId,
);
expect(JSON.parse(send?.json_cc ?? "null")).to.deep.equal([allowed]);
});
});
32 changes: 32 additions & 0 deletions packages/dms-mailing/src/test/unit/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,35 @@ describe("[unit] services/send missing system URLs", () => {
expect(refusedMissing(test, true, ["a"], SYSTEM)).to.deep.equal(["a"]);
});
});

describe("[unit] services/send copies and reply-to", () => {
const message = (
prepared: Partial<PreparedSend>,
replyTo: string,
): EmailParams =>
messageFor(
{
...input(RECIPIENTS),
prepared: { ...PREPARED, ...prepared },
settings: { ...SETTINGS, replyTo },
},
RECIPIENTS[0],
);

it("passes the copied addresses to the message", () => {
expect(message({ cc: ["boss@test.local"] }, "").cc).to.deep.equal([
"boss@test.local",
]);
expect(message({}, "").cc).to.equal(undefined);
});

it("prefers the send's reply-to over the workspace's", () => {
expect(
message({ replyTo: "per-send@test.local" }, "workspace@test.local")
.replyTo,
).to.equal("per-send@test.local");
expect(message({}, "workspace@test.local").replyTo).to.equal(
"workspace@test.local",
);
});
});
4 changes: 4 additions & 0 deletions packages/interface-dms-mailing/docs/1.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ interface SendTemplateParams {
source?: string;
isTest?: boolean;
attachments?: SendAttachment[];
cc?: EmailAddress[];
replyTo?: EmailAddress;
}

interface SendAttachment {
Expand Down Expand Up @@ -92,6 +94,8 @@ Validation failures reject the promise instead of returning recipient results. T

`attachments` sends files with the e-mail, the same for every recipient of the call. `content` holds the bytes the caller already read. The module keeps the last path segment of `filename`, without line breaks, and passes the files to the `@antelopejs/interface-email` provider. A call carries at most 10 files adding up to at most 10 MiB, or it rejects with `attachments_too_large` before anything is sent or logged. The send log keeps each file's name, type, size and SHA-256 (`json_attachments`), never its bytes, so the dashboard refuses to send it again (`409`, `no_replay_with_attachments`): the caller, which holds the files, sends it again.

`cc` copies the same addresses on every message of the call. An address on the tenant's suppression list is left out, and the send log keeps the copied ones (`json_cc`). There is no `bcc`. `replyTo` sets where replies go, instead of the workspace's reply-to address.

## `RecordEmailEvent`

```ts [Contract]
Expand Down
8 changes: 8 additions & 0 deletions packages/interface-dms-mailing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,14 @@ export interface SendTemplateParams {
* attachments cannot be sent again from the dashboard.
*/
attachments?: SendAttachment[];
/**
* Copied on every message of the send. An address on the tenant's
* suppression list is left out, and the send log keeps those that were
* copied. There is no `bcc`.
*/
cc?: EmailAddress[];
/** Where replies go, instead of the workspace's reply-to address. */
replyTo?: EmailAddress;
}

/**
Expand Down
Loading