import { sendEmail } from "@beenvoice/email"; process.env.EMAIL_PROVIDER = "mailpit"; process.env.EMAIL_FROM ??= "beenvoice "; 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<>endobj\n2 0 obj<>endobj\ntrailer<>\n%%EOF\n", ); const result = await sendEmail({ to: recipient, subject: "Beenvoice invoice delivery preview", html: "

Invoice delivery is working

This message verifies the Mailpit transport and PDF attachment path.

", 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, }), );