67 lines
2.1 KiB
JavaScript
67 lines
2.1 KiB
JavaScript
const nodemailer = require('nodemailer');
|
||
const logger = require('./logger');
|
||
|
||
/**
|
||
* Creates a nodemailer transporter from environment variables.
|
||
* Required env vars: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS
|
||
* Optional env vars: SMTP_FROM (defaults to SMTP_USER), SMTP_SECURE (defaults to 'true' if port 465)
|
||
*
|
||
* Returns null if SMTP is not configured so callers can fall back gracefully.
|
||
*/
|
||
const createTransport = () => {
|
||
const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS } = process.env;
|
||
if (!SMTP_HOST || !SMTP_USER || !SMTP_PASS) {
|
||
return null;
|
||
}
|
||
const port = parseInt(SMTP_PORT || '587', 10);
|
||
const secure = process.env.SMTP_SECURE !== undefined
|
||
? process.env.SMTP_SECURE === 'true'
|
||
: port === 465;
|
||
|
||
return nodemailer.createTransport({
|
||
host: SMTP_HOST,
|
||
port,
|
||
secure,
|
||
auth: { user: SMTP_USER, pass: SMTP_PASS }
|
||
});
|
||
};
|
||
|
||
/**
|
||
* Send a password-reset e-mail to the given address.
|
||
*
|
||
* @param {string} toEmail – recipient address
|
||
* @param {string} resetUrl – full URL including token query parameter
|
||
* @returns {Promise<boolean>} true if mail was sent, false if SMTP is not configured
|
||
*/
|
||
const sendPasswordResetMail = async (toEmail, resetUrl) => {
|
||
const transport = createTransport();
|
||
if (!transport) {
|
||
logger.warn(
|
||
'[mailer] SMTP nicht konfiguriert (SMTP_HOST/SMTP_USER/SMTP_PASS fehlen). ' +
|
||
'Reset-Link wird nur geloggt.'
|
||
);
|
||
return false;
|
||
}
|
||
|
||
const from = process.env.SMTP_FROM || process.env.SMTP_USER;
|
||
|
||
await transport.sendMail({
|
||
from,
|
||
to: toEmail,
|
||
subject: 'Passwort-Reset',
|
||
text:
|
||
`Sie haben einen Passwort-Reset angefordert.\n\n` +
|
||
`Klicken Sie auf den folgenden Link (gültig für 1 Stunde):\n${resetUrl}\n\n` +
|
||
`Falls Sie keinen Reset angefordert haben, ignorieren Sie diese Mail.`,
|
||
html:
|
||
`<p>Sie haben einen Passwort-Reset angefordert.</p>` +
|
||
`<p><a href="${resetUrl}">Passwort zurücksetzen</a></p>` +
|
||
`<p>Der Link ist 1 Stunde gültig.</p>` +
|
||
`<p>Falls Sie keinen Reset angefordert haben, ignorieren Sie diese Mail.</p>`
|
||
});
|
||
|
||
return true;
|
||
};
|
||
|
||
module.exports = { sendPasswordResetMail };
|