aboutsummaryrefslogtreecommitdiff
path: root/src/integrations/email.ts
blob: aa4c36c64b3117295bf520bdf8da36fb65ed418d (plain) (blame)
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
import { Either, type IEither } from '@emprespresso/pengueno';
import type { EmailConfig, StoredRequest } from '../types/index.js';
import nodemailer from 'nodemailer';

export async function sendEmailNotification(config: EmailConfig, request: StoredRequest): Promise<IEither<Error, void>> {
    if (!config.enabled || !config.to || !config.from) {
        return Either.right(<void>undefined);
    }

    return Either.fromFailableAsync(async () => {
        // Create transporter based on configuration
        const transporter = nodemailer.createTransport({
            host: config.host || 'localhost',
            port: config.port || 25,
            secure: config.secure ?? false,
            auth: config.username && config.password
                ? {
                    user: config.username,
                    pass: config.password,
                }
                : undefined,
        });

        const subject = config.subject || `Webhook received: ${request.routeName}`;

        // Build email body
        let htmlBody = `
            <h2>Webhook Notification</h2>
            <p><strong>Route:</strong> ${request.routeName}</p>
            <p><strong>Method:</strong> ${request.method}</p>
            <p><strong>Timestamp:</strong> ${new Date(request.timestamp).toISOString()}</p>
            <p><strong>UUID:</strong> ${request.uuid}</p>
        `;

        if (config.includeBody && request.body !== undefined) {
            htmlBody += `
                <h3>Request Body:</h3>
                <pre>${JSON.stringify(request.body, null, 2)}</pre>
            `;
        }

        if (config.includeHeaders && request.headers) {
            htmlBody += `
                <h3>Headers:</h3>
                <pre>${JSON.stringify(request.headers, null, 2)}</pre>
            `;
        }

        if (request.files && request.files.length > 0) {
            htmlBody += `
                <h3>Uploaded Files:</h3>
                <ul>
                    ${request.files.map(f => `<li>${f.originalFilename} (${f.contentType}, ${f.size} bytes)</li>`).join('')}
                </ul>
            `;
        }

        const mailOptions = {
            from: config.from,
            to: config.to,
            subject: subject,
            html: htmlBody,
        };

        await transporter.sendMail(mailOptions);

        return <void>undefined;
    });
}