agn-utils/mailer/mailer.js

84 lines
2.5 KiB
JavaScript

'use strict';
const nodemailer = require('nodemailer'),
debug = require('debug')('app:mailer');
const createConfig = (env) => {
const isSecure = env?.SMTP_SECURE || process.env.SMTP_SECURE || false;
const port = env?.SMTP_PORT || process.env.SMTP_PORT || 587;
const config = {
host: env?.SMTP_HOST || process.env.SMTP_HOST,
port: port,
secure: isSecure,
auth: {
user: env?.SMTP_USR || process.env.SMTP_USR,
pass: env?.SMTP_PWD || process.env.SMTP_PWD,
},
sender: env?.SMTP_SENDER || process.env.SMTP_SENDER || `"AgNav Inc." <noreply@agnav.com>`
};
if (!config.host || !config.port || !config.auth.user || !config.auth.pass) {
throw new Error('SMTP configuration is missing required fields (host, port, user, pass).');
}
return config;
};
const createMailOptions = (from, to, subject, body) => ({
from: from, to: to, subject: subject, text: body
});
function createMailer(env) {
const config = createConfig(env);
const transporter = nodemailer.createTransport(config);
return {
sendMail: async (to, subject, body) => {
try {
if (!to || !subject || !body) {
throw new Error('Missing required fields: to, subject, or body');
}
const mailOptions = createMailOptions(config.sender, to, subject, body);
const info = await transporter.sendMail(mailOptions);
return { success: true, message: 'Mail sent successfully', messageId: info.messageId };
} catch (error) {
debug('Error sending mail:', error.message);
return { success: false, error: error.message };
}
},
};
}
/**
* Send a text email
* @param {Object} options Email options
* @param {string} options.from Sender of the email (Optional)
* @param {string} options.subject Subject of the email
* @param {string} options.to Recipient of the email
* @param {string} options.text Text content of the email
*/
async function sendTextMail(options, env) {
const { from, to, subject, body } = options;
if (!to || !subject || !body) {
throw new Error('Missing required fields: to, subject, or body');
}
const config = createConfig(env);
const transporter = nodemailer.createTransport(config);
const mailOptions = createMailOptions(from || config.sender, to, subject, body);
try {
const info = await transporter.sendMail(mailOptions);
return { success: true, messageId: info.messageId };
} catch (error) {
debug('Error sending email:', error.message);
return { success: false, error: error.message };
}
}
module.exports = {
createMailer, sendTextMail
};