const nodemailer = require('nodemailer'); const { smtpSettings } = require('./settings'); // SMTP is set on the Settings page; the transporter is rebuilt when those settings change. let transporter = null; let transporterFor = ''; function createTransport(smtp) { return nodemailer.createTransport({ host: smtp.host, port: smtp.port, secure: smtp.port === 465, auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined, connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 30000, }); } function fromAddress(smtp) { return smtp.from || smtp.user || 'hub@localhost'; } async function smtpConfigured() { return !!(await smtpSettings()).host; } /** * Send an email; without SMTP it's logged instead (development). Billing emails (1.7.0) add * `html`, `attachments` (nodemailer's: { filename, content, contentType, cid? }), `replyTo` and * `fromName` (shown as the sender's name). */ async function sendMail({ to, subject, text, html, attachments, replyTo, fromName }) { if (!to) return; const smtp = await smtpSettings(); if (!smtp.host) { const files = (attachments || []).filter(a => !a.cid).map(a => a.filename).join(', '); console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"${files ? ` attachments=${files}` : ''}\n${text}`); return; } const key = JSON.stringify(smtp); if (!transporter || transporterFor !== key) { transporter = createTransport(smtp); transporterFor = key; } const address = fromAddress(smtp); const from = fromName ? { name: fromName, address: address.replace(/^.*<([^>]+)>.*$/, '$1') } : address; await transporter.sendMail({ from, to, subject, text, html, attachments, replyTo }); } /** * Check SMTP settings (saved, or `overrides` from the form before saving): log in to the * server, then send a test email to `to`. Throws with the server's reason if either fails. */ async function testSmtp(overrides, to) { const smtp = await smtpSettings(overrides); if (!smtp.host) throw new Error('Enter the SMTP server first.'); const t = createTransport(smtp); try { await t.verify(); await t.sendMail({ from: fromAddress(smtp), to, subject: 'Cross Events Hub: test email', text: `This is a test email from the Cross Events Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`, }); } finally { t.close(); } } module.exports = { sendMail, smtpConfigured, testSmtp };