swadhinbiswas Add user email delivery test API · 2/19/2026
633bfd6
290 lines · 9.2 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/**
 * Email Service
 * Handles sending emails using nodemailer
 */

import { logger } from "./logger";

const SMTP_HOST = import.meta.env.SMTP_HOST;
const SMTP_PORT = parseInt(import.meta.env.SMTP_PORT || "587");
const SMTP_USER = import.meta.env.SMTP_USER;
const SMTP_PASSWORD = import.meta.env.SMTP_PASSWORD;
const SMTP_FROM = import.meta.env.SMTP_FROM || "[email protected]";
const SITE_URL = import.meta.env.SITE_URL || "http://localhost:4321";

export interface EmailOptions {
  to: string;
  subject: string;
  text?: string;
  html?: string;
}

export function isSmtpConfigured(): boolean {
  return Boolean(SMTP_HOST);
}

let transporter: any = null;

async function getTransporter() {
  if (transporter) return transporter;

  if (!SMTP_HOST) {
    logger.warn("SMTP not configured, emails will be logged only");
    return null;
  }

  try {
    const nodemailer = await import("nodemailer");
    transporter = nodemailer.createTransport({
      host: SMTP_HOST,
      port: SMTP_PORT,
      secure: SMTP_PORT === 465,
      auth: SMTP_USER ? {
        user: SMTP_USER,
        pass: SMTP_PASSWORD,
      } : undefined,
    });

    // Verify connection
    await transporter.verify();
    logger.info("SMTP connection verified");
    return transporter;
  } catch (error) {
    logger.error({ error }, "Failed to create SMTP transporter");
    return null;
  }
}

export async function sendEmail(options: EmailOptions): Promise<boolean> {
  try {
    const transport = await getTransporter();

    if (!transport) {
      // Log email for development/testing
      logger.info({
        to: options.to,
        subject: options.subject
      }, "Email would be sent (SMTP not configured)");
      return true;
    }

    await transport.sendMail({
      from: SMTP_FROM,
      to: options.to,
      subject: options.subject,
      text: options.text,
      html: options.html,
    });

    logger.info({ to: options.to, subject: options.subject }, "Email sent");
    return true;
  } catch (error) {
    logger.error({ error, to: options.to }, "Failed to send email");
    return false;
  }
}

export async function sendTestEmail(options: {
  to: string;
  dryRun?: boolean;
}): Promise<boolean> {
  const dryRun = options.dryRun ?? true;
  if (dryRun) {
    logger.info({ to: options.to }, "Test email dry-run (not sent)");
    return true;
  }

  return sendEmail({
    to: options.to,
    subject: "OpenCodeHub email delivery test",
    text: "This is a test email from OpenCodeHub. If you received this, email delivery is working.",
    html: `
      <div style="font-family: sans-serif; color: #111; line-height: 1.5;">
        <h2>OpenCodeHub email delivery test</h2>
        <p>This is a test email from OpenCodeHub.</p>
        <p>If you received this, your email delivery configuration is working.</p>
      </div>
    `,
  });
}

export async function sendPasswordResetEmail(email: string, token: string): Promise<boolean> {
  const resetUrl = `${SITE_URL}/reset-password?token=${token}`;

  return sendEmail({
    to: email,
    subject: "Reset your OpenCodeHub password",
    text: `
You requested a password reset for your OpenCodeHub account.

Click the link below to reset your password:
${resetUrl}

This link will expire in 1 hour.

If you didn't request this, you can safely ignore this email.
    `.trim(),
    html: `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #0d1117; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #0d1117; padding: 40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #161b22; border-radius: 12px; border: 1px solid #30363d;">
          <tr>
            <td style="padding: 40px;">
              <h1 style="margin: 0 0 24px; color: #f0f6fc; font-size: 24px;">Reset Your Password</h1>
              <p style="margin: 0 0 24px; color: #8b949e; font-size: 16px; line-height: 1.5;">
                You requested a password reset for your OpenCodeHub account. Click the button below to set a new password.
              </p>
              <a href="${resetUrl}" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #22d3ee, #a855f7); color: #fff; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;">
                Reset Password
              </a>
              <p style="margin: 24px 0 0; color: #6e7681; font-size: 14px;">
                This link will expire in 1 hour. If you didn't request this, you can safely ignore this email.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding: 20px 40px; border-top: 1px solid #30363d;">
              <p style="margin: 0; color: #6e7681; font-size: 12px;">
                © ${new Date().getFullYear()} OpenCodeHub. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
    `.trim(),
  });
}

export async function sendVerificationEmail(email: string, token: string): Promise<boolean> {
  const verifyUrl = `${SITE_URL}/verify-email?token=${token}`;

  return sendEmail({
    to: email,
    subject: "Verify your OpenCodeHub email",
    text: `
Welcome to OpenCodeHub!

Please verify your email by clicking the link below:
${verifyUrl}

This link will expire in 24 hours.
    `.trim(),
    html: `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #0d1117; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #0d1117; padding: 40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #161b22; border-radius: 12px; border: 1px solid #30363d;">
          <tr>
            <td style="padding: 40px;">
              <h1 style="margin: 0 0 24px; color: #f0f6fc; font-size: 24px;">Welcome to OpenCodeHub! 🎉</h1>
              <p style="margin: 0 0 24px; color: #8b949e; font-size: 16px; line-height: 1.5;">
                Thanks for signing up! Please verify your email address to get started.
              </p>
              <a href="${verifyUrl}" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #22d3ee, #a855f7); color: #fff; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;">
                Verify Email
              </a>
              <p style="margin: 24px 0 0; color: #6e7681; font-size: 14px;">
                This link will expire in 24 hours.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding: 20px 40px; border-top: 1px solid #30363d;">
              <p style="margin: 0; color: #6e7681; font-size: 12px;">
                © ${new Date().getFullYear()} OpenCodeHub. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
    `.trim(),
  });
}

export async function sendPullRequestEmail(
  to: string,
  type: "opened" | "merged" | "closed" | "review_requested",
  pr: {
    title: string;
    number: number;
    url: string;
    repository: { name: string; owner: { username: string } };
    author: { username: string };
  }
): Promise<boolean> {
  const subjectPrefix = `[${pr.repository.owner.username}/${pr.repository.name}]`;
  let action = "";
  switch (type) {
    case "opened": action = "opened"; break;
    case "merged": action = "merged"; break;
    case "closed": action = "closed"; break;
    case "review_requested": action = "requested your review on"; break;
  }

  return sendEmail({
    to,
    subject: `${subjectPrefix} PR #${pr.number} ${action}: ${pr.title}`,
    html: `
            <div style="font-family: sans-serif; color: #333;">
                <h3>Pull Request ${action}</h3>
                <p>
                    <strong>${pr.author.username}</strong> ${action} pull request 
                    <a href="${pr.url}">#${pr.number}: ${pr.title}</a>
                </p>
            </div>
        `
  });
}

export async function sendIssueEmail(
  to: string,
  type: "opened" | "closed" | "assigned",
  issue: {
    title: string;
    number: number;
    url: string;
    repository: { name: string; owner: { username: string } };
    author: { username: string };
  }
): Promise<boolean> {
  const subjectPrefix = `[${issue.repository.owner.username}/${issue.repository.name}]`;
  let action = type;

  return sendEmail({
    to,
    subject: `${subjectPrefix} Issue #${issue.number} ${action}: ${issue.title}`,
    html: `
            <div style="font-family: sans-serif; color: #333;">
                <h3>Issue ${action}</h3>
                <p>
                    <strong>${issue.author.username}</strong> ${action} issue 
                    <a href="${issue.url}">#${issue.number}: ${issue.title}</a>
                </p>
            </div>
        `
  });
}