📧 feat: Allow usage of custom SMTP server (#1219)

Co-authored-by: David Reis <post@d-reis.com>
This commit is contained in:
David 2023-11-29 00:00:07 +01:00 committed by GitHub
parent 3838ff4617
commit ae03267d9b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 155 additions and 85 deletions

View file

@ -22,7 +22,7 @@ router.get('/', async function (req, res) {
registrationEnabled: isEnabled(process.env.ALLOW_REGISTRATION),
socialLoginEnabled: isEnabled(process.env.ALLOW_SOCIAL_LOGIN),
emailEnabled:
!process.env.EMAIL_SERVICE &&
(!!process.env.EMAIL_SERVICE || !!process.env.EMAIL_HOST) &&
!!process.env.EMAIL_USERNAME &&
!!process.env.EMAIL_PASSWORD &&
!!process.env.EMAIL_FROM,

View file

@ -131,7 +131,7 @@ const requestPasswordReset = async (email) => {
const link = `${domains.client}/reset-password?token=${resetToken}&userId=${user._id}`;
const emailEnabled =
!!process.env.EMAIL_SERVICE &&
(!!process.env.EMAIL_SERVICE || !!process.env.EMAIL_HOST) &&
!!process.env.EMAIL_USERNAME &&
!!process.env.EMAIL_PASSWORD &&
!!process.env.EMAIL_FROM;

View file

@ -5,20 +5,50 @@ const path = require('path');
const sendEmail = async (email, subject, payload, template) => {
try {
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
const transporterOptions = {
// Use STARTTLS by default instead of obligatory TLS
secure: process.env.EMAIL_ENCRYPTION === "tls",
// If explicit STARTTLS is set, require it when connecting
requireTls: process.env.EMAIL_ENCRYPTION === "starttls",
tls: {
// Whether to accept unsigned certificates
rejectUnauthorized: process.env.EMAIL_ALLOW_SELFSIGNED === "true"
},
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
}
if (process.env.EMAIL_ENCRYPTION_HOSTNAME) {
// Check the certificate against this name explicitly
transporterOptions.tls.servername = process.env.EMAIL_ENCRYPTION_HOSTNAME;
}
// Mailer service definition has precedence
if (process.env.EMAIL_SERVICE) {
transporterOptions.service = process.env.EMAIL_SERVICE;
} else {
transporterOptions.host = process.env.EMAIL_HOST;
transporterOptions.port = process.env.EMAIL_PORT ?? 25;
}
const transporter = nodemailer.createTransport(transporterOptions);
const source = fs.readFileSync(path.join(__dirname, 'emails', template), 'utf8');
const compiledTemplate = handlebars.compile(source);
const options = () => {
return {
from: process.env.EMAIL_FROM,
to: email,
// Header address should contain name-addr
from: `"${process.env.EMAIL_FROM_NAME || process.env.APP_TITLE}"` +
`<${process.env.EMAIL_FROM}>`,
to: `"${payload.name}" <${email}>`,
envelope: {
// Envelope from should contain addr-spec
// Mistake in the Nodemailer documentation?
from: process.env.EMAIL_FROM,
to: email,
},
subject: subject,
html: compiledTemplate(payload),
};