-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailer.ts
More file actions
64 lines (56 loc) · 1.84 KB
/
Copy pathmailer.ts
File metadata and controls
64 lines (56 loc) · 1.84 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
import nodemailer from "nodemailer";
const smtpHost = process.env.SMTP_HOST;
const smtpPort = Number(process.env.SMTP_PORT ?? 587);
const smtpUser = process.env.SMTP_USER;
const smtpPass = process.env.SMTP_PASS;
const smtpFrom =
process.env.SMTP_FROM ?? (smtpUser ? `"Auth App" <${smtpUser}>` : "no-reply@localhost");
const smtpConfigured = Boolean(smtpHost && smtpUser && smtpPass);
/**
* If SMTP credentials are configured we send real emails through nodemailer.
* Otherwise we fall back to nodemailer's jsonTransport, which "sends" the
* message and lets us log it to the server console (handy for local dev).
*/
const transport = smtpConfigured
? nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: { user: smtpUser!, pass: smtpPass! },
})
: nodemailer.createTransport({ jsonTransport: true });
export interface SendEmailInput {
to: string;
subject: string;
html: string;
text?: string;
}
export async function sendEmail({ to, subject, html, text }: SendEmailInput) {
const info = await transport.sendMail({
from: smtpFrom,
to,
subject,
html,
text: text ?? html.replace(/<[^>]*>/g, " "),
});
if (!smtpConfigured) {
// Dev fallback: log the message envelope so the email is visible.
const message = (info as unknown as { message?: string }).message;
if (message) {
try {
const parsed = JSON.parse(message);
console.log(
`[mailer:dev] Email sent to ${to} (subject: "${subject}")\n${parsed.text ?? parsed.html ?? ""}`,
);
} catch {
console.log(`[mailer:dev] Email sent to ${to} (subject: "${subject}")`);
}
} else {
console.log(`[mailer:dev] Email sent to ${to} (subject: "${subject}")`);
}
}
return info;
}
export function isSmtpConfigured() {
return smtpConfigured;
}