Add Mailpit email transport
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { sendEmail } from "@beenvoice/email";
|
||||
|
||||
process.env.EMAIL_PROVIDER = "mailpit";
|
||||
process.env.EMAIL_FROM ??= "beenvoice <noreply@beenvoice.test>";
|
||||
process.env.SMTP_HOST ??= "127.0.0.1";
|
||||
process.env.SMTP_PORT ??= "1028";
|
||||
process.env.SMTP_SECURE ??= "false";
|
||||
|
||||
const recipient =
|
||||
process.env.EMAIL_PREVIEW_TO ?? "invoice-preview@beenvoice.test";
|
||||
const mailpitApiUrl =
|
||||
process.env.MAILPIT_API_URL?.replace(/\/$/, "") ?? "http://127.0.0.1:8028";
|
||||
const referenceId = `beenvoice-preview-${crypto.randomUUID()}`;
|
||||
const previewPdf = Buffer.from(
|
||||
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 0>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n",
|
||||
);
|
||||
|
||||
const result = await sendEmail({
|
||||
to: recipient,
|
||||
subject: "Beenvoice invoice delivery preview",
|
||||
html: "<h1>Invoice delivery is working</h1><p>This message verifies the Mailpit transport and PDF attachment path.</p>",
|
||||
text: "Invoice delivery is working. This message verifies the Mailpit transport and PDF attachment path.",
|
||||
idempotencyKey: referenceId,
|
||||
attachments: [
|
||||
{
|
||||
filename: "invoice-preview.pdf",
|
||||
content: previewPdf,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
type MailpitMessageSummary = {
|
||||
ID: string;
|
||||
MessageID: string;
|
||||
Attachments: number;
|
||||
};
|
||||
|
||||
let captured: MailpitMessageSummary | undefined;
|
||||
const expectedMessageId = result.id.replace(/^<|>$/g, "");
|
||||
for (let attempt = 0; attempt < 10 && !captured; attempt += 1) {
|
||||
const response = await fetch(`${mailpitApiUrl}/api/v1/messages`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Mailpit API returned ${response.status}`);
|
||||
}
|
||||
const body = (await response.json()) as {
|
||||
messages?: MailpitMessageSummary[];
|
||||
};
|
||||
captured = body.messages?.find(
|
||||
(message) => message.MessageID === expectedMessageId,
|
||||
);
|
||||
if (!captured) await Bun.sleep(100);
|
||||
}
|
||||
|
||||
if (!captured) throw new Error("Mailpit did not capture the preview message");
|
||||
if (captured.Attachments !== 1) {
|
||||
throw new Error("Mailpit did not capture the invoice PDF attachment");
|
||||
}
|
||||
|
||||
console.info(
|
||||
JSON.stringify({
|
||||
provider: result.provider,
|
||||
recipient,
|
||||
messageId: result.id,
|
||||
referenceId,
|
||||
mailpitMessageId: captured.ID,
|
||||
attachmentCount: captured.Attachments,
|
||||
}),
|
||||
);
|
||||
Reference in New Issue
Block a user