All files / lib/email/providers mailtrap.provider.ts

100% Statements 18/18
100% Branches 6/6
100% Functions 2/2
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                              10x 10x   10x 10x 3x 3x   7x 7x                 6x   6x                           6x 1x 1x 1x         5x         5x     6x 6x      
import type { EmailProvider, EmailConfig } from "./base";
 
/**
 * Mailtrap Sandbox email provider for dev/preview environments.
 *
 * Sends to a virtual inbox — no real email delivery.
 * API: https://sandbox.api.mailtrap.io/api/send/{inbox_id}
 */
export class MailtrapProvider implements EmailProvider {
	private apiUrl: string;
	private apiToken: string;
	private fromEmail: string;
	private fromName: string;
 
	constructor(apiToken: string, inboxId: string, config: EmailConfig) {
		this.apiUrl = `https://sandbox.api.mailtrap.io/api/send/${inboxId}`;
		this.apiToken = apiToken;
		// Parse "Name <email>" format, or use as-is
		const match = config.from.match(/^(.+?)\s*<(.+?)>$/);
		if (match) {
			this.fromName = match[1].trim();
			this.fromEmail = match[2].trim();
		} else {
			this.fromName = "Interioring";
			this.fromEmail = config.from;
		}
	}
 
	async sendEmail(params: {
		to: string;
		subject: string;
		html: string;
	}): Promise<{ id: string }> {
		const { to, subject, html } = params;
 
		const response = await fetch(this.apiUrl, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"Api-Token": this.apiToken,
			},
			body: JSON.stringify({
				from: { email: this.fromEmail, name: this.fromName },
				to: [{ email: to }],
				subject,
				html,
			}),
		});
 
		if (!response.ok) {
			const errorText = await response.text();
			console.error("[EMAIL-MAILTRAP] Failed to send:", errorText);
			throw new Error(
				`Failed to send email via Mailtrap: ${response.status} ${response.statusText}`,
			);
		}
 
		const data = (await response.json()) as {
			success?: boolean;
			message_ids?: string[];
		};
		const messageId =
			data.message_ids?.[0] ||
			`mailtrap-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
 
		console.log(`[EMAIL-MAILTRAP] Email sent to ${to}: ${subject}`);
		return { id: messageId };
	}
}