UNPKG

@coko/server

Version:

Reusable server for use by Coko's projects

67 lines 2.51 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeTransportConfig = exports.sendEmail = void 0; const nodemailer_1 = __importDefault(require("nodemailer")); const config_1 = __importDefault(require("../configManager/config")); const logger_1 = __importDefault(require("../logger")); const SendEmailError_1 = __importDefault(require("./SendEmailError")); const makeTransportConfig = async (configObject, mailerConfigOverrides = {}) => { const isProduction = process.env.NODE_ENV === 'production'; const globalConfig = (configObject.has('mailer.transport') && configObject.get('mailer.transport')) || {}; let configToUse; const foundConfig = { ...globalConfig, ...mailerConfigOverrides, }; const hasConfig = Object.keys(foundConfig).length > 0 && foundConfig.host && foundConfig.port && foundConfig.auth?.user && foundConfig.auth?.pass; let testTransportUsed = false; if (hasConfig) configToUse = foundConfig; if (!hasConfig && !isProduction) { const ethereal = await nodemailer_1.default.createTestAccount(); configToUse = { ...ethereal.smtp, auth: { user: ethereal.user, pass: ethereal.pass, }, }; testTransportUsed = true; } if (!configToUse) { throw new SendEmailError_1.default(`Mailer configuration is missing`); } return { transportConfig: configToUse, testTransportUsed, }; }; exports.makeTransportConfig = makeTransportConfig; const sendEmail = async (mailData, mailerConfigOverrides = {}) => { try { const { transportConfig, testTransportUsed } = await makeTransportConfig(config_1.default, mailerConfigOverrides); const transporter = nodemailer_1.default.createTransport(transportConfig); const info = await transporter.sendMail({ from: config_1.default.get('mailer.from'), ...mailData, }); if (testTransportUsed) { logger_1.default.info(`Email preview available at: ${nodemailer_1.default.getTestMessageUrl(info)}`); } return info; } catch (e) { throw new SendEmailError_1.default(e); } }; exports.sendEmail = sendEmail; //# sourceMappingURL=sendEmail.js.map