Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Carlos redo anniversary celebrated #1185

Merged
merged 3 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
Loading