summaryrefslogtreecommitdiff
path: root/src/lib/email.ts
blob: 82dd48e928298919bd87297887411f2992920f8f (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { Request } from "express";
import sgMail from "@sendgrid/mail";
import nodemailer from "nodemailer";
import { getConfig } from "./config.js";
import SMTPTransport from "nodemailer/lib/smtp-transport/index.js";
import { exitWithError } from "./process.js";
import { renderTemplate } from "./handlebars.js";
const config = getConfig();

type EmailTemplate =
    | "addEventAttendee"
    | "addEventComment"
    | "createEvent"
    | "createEventGroup"
    | "createEventMagicLink"
    | "deleteEvent"
    | "editEvent"
    | "eventGroupUpdated"
    | "subscribed"
    | "unattendEvent";

export const initEmailService = async (): Promise<boolean> => {
    if (process.env.CYPRESS || process.env.CI) {
        console.log(
            "Running in Cypress or CI, not initializing email service.",
        );
        return false;
    }
    switch (config.general.mail_service) {
        case "sendgrid":
            if (!config.sendgrid?.api_key) {
                return exitWithError(
                    "Sendgrid is configured as the email service, but no API key is provided. Please provide an API key in the config file.",
                );
            }
            sgMail.setApiKey(config.sendgrid.api_key);
            console.log("Sendgrid is ready to send emails.");
            return true;
        case "nodemailer":
            if (
                !config.nodemailer?.smtp_server ||
                !config.nodemailer?.smtp_port
            ) {
                return exitWithError(
                    "Nodemailer is configured as the email service, but not all required fields are provided. Please provide all required fields in the config file.",
                );
            }
            const nodemailerConfig = {
                host: config.nodemailer?.smtp_server,
                port: Number(config.nodemailer?.smtp_port) || 587,
                tls: { 
                    // do not fail on invalid certs
                    rejectUnauthorized: false,
                },
            } as SMTPTransport.Options;

            if (config.nodemailer?.smtp_username) {
                nodemailerConfig.auth = {
                    user: config.nodemailer?.smtp_username,
                    pass: config.nodemailer?.smtp_password
                };
            }

            const nodemailerTransporter =
                nodemailer.createTransport(nodemailerConfig);
            const nodemailerVerified = await nodemailerTransporter.verify();
            if (nodemailerVerified) {
                console.log("Nodemailer is ready to send emails.");
                return true;
            } else {
                return exitWithError(
                    "Error verifying Nodemailer transporter. Please check your Nodemailer configuration.",
                );
            }
        case "none":
        default:
            console.warn(
                "You have not configured this Gathio instance to send emails! This means that event creators will not receive emails when their events are created, which means they may end up locked out of editing events. Consider setting up an email service.",
            );
            return false;
    }
};

export const sendEmail = async (
    to: string,
    bcc: string,
    subject: string,
    text: string,
    html?: string,
): Promise<boolean> => {
    switch (config.general.mail_service) {
        case "sendgrid":
            try {
                await sgMail.send({
                    to,
                    bcc,
                    from: config.general.email,
                    subject: `${config.general.site_name}: ${subject}`,
                    text,
                    html,
                });
                return true;
            } catch (e: any) {
                if (e.response) {
                    console.error(e.response.body);
                } else {
                    console.error(e);
                }
                return false;
            }
        case "nodemailer":
            try {
                const nodemailerConfig = {
                    host: config.nodemailer?.smtp_server,
                    port: Number(config.nodemailer?.smtp_port) || 587,
                } as SMTPTransport.Options;

                if (config.nodemailer?.smtp_username) {
                    nodemailerConfig.auth = {
                        user: config.nodemailer?.smtp_username,
                        pass: config.nodemailer?.smtp_password
                    };
                }

                const nodemailerTransporter =
                    nodemailer.createTransport(nodemailerConfig);
                await nodemailerTransporter.sendMail({
                    envelope: {
                        from: config.general.email,
                        to,
                        bcc,
                    },
                    from: config.general.email,
                    to,
                    bcc,
                    subject,
                    text,
                    html,
                });
                return true;
            } catch (e) {
                console.error(e);
                return false;
            }
        default:
            return false;
    }
};

export const sendEmailFromTemplate = async (
    to: string,
    bcc: string,
    subject: string,
    template: EmailTemplate,
    templateData: Record<string, unknown>,
    req: Request,
): Promise<boolean> => {
    const html = await renderTemplate(req, `${template}/${template}Html`, {
        siteName: config.general.site_name,
        siteLogo: config.general.email_logo_url,
        domain: config.general.domain,
        cache: true,
        layout: "email.handlebars",
        ...templateData,
    });
    const text = await renderTemplate(
        req,
        `${template}/${template}Text`,
        templateData,
    );
    return await sendEmail(to, bcc, subject, text, html);
};