Skip to content

Commit

Permalink
Merge pull request #1185 from OneCommunityGlobal/Carlos-Anniversary-C…
Browse files Browse the repository at this point in the history
…elebrated

Carlos redo anniversary celebrated
  • Loading branch information
one-community authored Jan 16, 2025
2 parents d57c0d1 + 2f84535 commit b13e8bb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 35 deletions.
20 changes: 2 additions & 18 deletions src/controllers/emailController.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,32 +70,19 @@ const sendEmail = async (req, res) => {
if (!subject) missingFields.push('Subject');
if (!html) missingFields.push('HTML content');
if (!to) missingFields.push('Recipient email');
console.log('missingFields', missingFields);
return res
.status(400)
.send(`${missingFields.join(' and ')} ${missingFields.length > 1 ? 'are' : 'is'} required`);
}

// Extract images and create attachments
const { html: processedHtml, attachments } = extractImagesAndCreateAttachments(html);

// Log recipient for debugging
console.log('Recipient:', to);


await emailSender(to, subject, html)
.then(result => {
console.log('Email sent successfully:', result);
.then(() => {
res.status(200).send(`Email sent successfully to ${to}`);
})
.catch(error => {
console.error('Error sending email:', error);
.catch(() => {
res.status(500).send('Error sending email');
});


} catch (error) {
console.error('Error sending email:', error);
return res.status(500).send('Error sending email');
}
};
Expand Down Expand Up @@ -129,14 +116,12 @@ const sendEmailToAll = async (req, res) => {
if (recipientEmails.length === 0) {
throw new Error('No recipients defined');
}

const emailContentToOCmembers = handleContentToOC(processedHtml);
await Promise.all(
recipientEmails.map((email) =>
emailSender(email, subject, emailContentToOCmembers, attachments),
),
);

const emailSubscribers = await EmailSubcriptionList.find({ email: { $exists: true, $ne: '' } });
console.log('# sendEmailToAll emailSubscribers', emailSubscribers.length);
await Promise.all(
Expand All @@ -145,7 +130,6 @@ const sendEmailToAll = async (req, res) => {
return emailSender(email, subject, emailContentToNonOCmembers, attachments);
}),
);

return res.status(200).send('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
Expand Down
41 changes: 24 additions & 17 deletions src/utilities/emailSender.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const transporter = nodemailer.createTransport({
const sendEmail = async (mailOptions) => {
try {
const { token } = await OAuth2Client.getAccessToken();

mailOptions.auth = {
user: config.email,
refreshToken: config.refreshToken,
Expand All @@ -45,6 +46,7 @@ const sendEmail = async (mailOptions) => {
}
return result;
} catch (error) {
console.error('Error sending email:', error);
logger.logException(error, `Error sending email: ${mailOptions.to}`);
throw error;
}
Expand All @@ -57,7 +59,6 @@ const processQueue = async () => {
if (isProcessing || queue.length === 0) return;

isProcessing = true;
console.log('Processing email queue...');

const processBatch = async () => {
if (queue.length === 0) {
Expand All @@ -67,12 +68,10 @@ const processQueue = async () => {

const batch = queue.shift();
try {
console.log('Sending email...');
await sendEmail(batch);
} catch (error) {
logger.logException(error, 'Failed to send email batch');
}

setTimeout(processBatch, config.rateLimitDelay);
};

Expand All @@ -94,21 +93,29 @@ const emailSender = (
replyTo = null,
) => {
if (!process.env.sendEmail) return;
const recipientsArray = Array.isArray(recipients) ? recipients : [recipients];
for (let i = 0; i < recipients.length; i += config.batchSize) {
const batchRecipients = recipientsArray.slice(i, i + config.batchSize);
queue.push({
from: config.email,
bcc: batchRecipients.join(','),
subject,
html: message,
attachments,
cc,
replyTo,
return new Promise((resolve, reject) => {
const recipientsArray = Array.isArray(recipients) ? recipients : [recipients];
for (let i = 0; i < recipients.length; i += config.batchSize) {
const batchRecipients = recipientsArray.slice(i, i + config.batchSize);
queue.push({
from: config.email,
bcc: batchRecipients.join(','),
subject,
html: message,
attachments,
cc,
replyTo,
});
}
setImmediate(async () => {
try {
await processQueue();
resolve('Emails processed successfully');
} catch (error) {
reject(error);
}
});
}
console.log('Emails queued:', queue.length);
setImmediate(processQueue);
});
};

module.exports = emailSender;

0 comments on commit b13e8bb

Please sign in to comment.