43 lines
1.5 KiB
JavaScript
43 lines
1.5 KiB
JavaScript
// SMTP delivery for account notifications.
|
|
|
|
const nodemailer = require('nodemailer');
|
|
|
|
function getSmtpConfig(settings) {
|
|
return {
|
|
enabled: Boolean(settings['email.smtp_enabled']),
|
|
host: String(settings['email.smtp_host'] || '').trim(),
|
|
port: Number(settings['email.smtp_port']) || 587,
|
|
security: String(settings['email.smtp_security'] || 'starttls'),
|
|
username: String(settings['email.smtp_username'] || '').trim(),
|
|
password: String(settings['email.smtp_password'] || ''),
|
|
fromAddress: String(settings['email.from_address'] || '').trim(),
|
|
fromName: String(settings['email.from_name'] || '').trim()
|
|
};
|
|
}
|
|
|
|
function createMailTransport(settings) {
|
|
const config = getSmtpConfig(settings);
|
|
if (!config.enabled || !config.host || !config.fromAddress) {
|
|
return null;
|
|
}
|
|
return nodemailer.createTransport({
|
|
host: config.host,
|
|
port: config.port,
|
|
secure: config.security === 'tls',
|
|
requireTLS: config.security === 'starttls',
|
|
auth: config.username ? { user: config.username, pass: config.password } : undefined
|
|
});
|
|
}
|
|
|
|
async function sendAccountEmail(settings, message) {
|
|
const transport = createMailTransport(settings);
|
|
if (!transport) {
|
|
throw new Error('Email delivery is not configured.');
|
|
}
|
|
const config = getSmtpConfig(settings);
|
|
return transport.sendMail(Object.assign({}, message, {
|
|
from: config.fromName ? '"' + config.fromName.replace(/"/g, '') + '" <' + config.fromAddress + '>' : config.fromAddress,
|
|
}));
|
|
}
|
|
|
|
module.exports = { getSmtpConfig, createMailTransport, sendAccountEmail }; |