source: Klonkt/src/config/mailer.js@ c6cdce6

main
Last change on this file since c6cdce6 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 2.1 KB
Line 
1// Send email (password reset, newsletter, notify). Optional: only active
2// when SMTP is configured — via Admin → Settings (app_settings) OR env vars.
3//
4// Config source (in this order): app_settings (set via the UI), otherwise env:
5// SMTP_HOST, SMTP_PORT (default 587), SMTP_USER, SMTP_PASS, SMTP_FROM (default = USER)
6// Not configured → sending falls back to CLI (reset-admin) / is skipped.
7
8import nodemailer from 'nodemailer';
9import { getSetting } from '../services/SettingsService.js';
10
11function cfg() {
12 const host = getSetting('smtp_host', '') || process.env.SMTP_HOST || '';
13 const port = parseInt(getSetting('smtp_port', '') || process.env.SMTP_PORT || '587', 10) || 587;
14 const user = getSetting('smtp_user', '') || process.env.SMTP_USER || '';
15 const pass = getSetting('smtp_pass', '') || process.env.SMTP_PASS || '';
16 const from = getSetting('smtp_from', '') || process.env.SMTP_FROM || user;
17 return { host, port, user, pass, from };
18}
19
20export function mailerConfigured() {
21 const c = cfg();
22 return !!(c.host && c.user && c.pass);
23}
24
25// Status for the UI (without leaking the password).
26export function mailerStatus() {
27 const c = cfg();
28 return {
29 configured: mailerConfigured(),
30 host: c.host,
31 port: c.port,
32 user: c.user,
33 from: c.from,
34 passSet: !!c.pass,
35 // source: useful to show that env vars are still active
36 fromEnv: !getSetting('smtp_host', '') && !!process.env.SMTP_HOST,
37 };
38}
39
40// Cache the transport, but rebuild it whenever the config changes (UI edit without restart).
41let _transport = null, _key = null;
42function transport() {
43 const c = cfg();
44 const key = [c.host, c.port, c.user, c.pass].join('|');
45 if (!_transport || _key !== key) {
46 _transport = nodemailer.createTransport({
47 host: c.host,
48 port: c.port,
49 secure: c.port === 465, // 465 = implicit TLS; 587 = STARTTLS
50 auth: { user: c.user, pass: c.pass },
51 });
52 _key = key;
53 }
54 return _transport;
55}
56
57export async function sendMail({ to, subject, text, html }) {
58 if (!mailerConfigured()) throw new Error('SMTP not configured');
59 const c = cfg();
60 return transport().sendMail({ from: c.from, to, subject, text, html });
61}
Note: See TracBrowser for help on using the repository browser.