Description:
I am facing one weird bug where SendGrid stops sending mail after 20-24 hours of inactivity. That is if no mail has been sent for 20-24 hr since the last sent mail, then after that Sendgrid stops sending mail to every email. As a solution, I have to start the server locally and hit any API that triggers the mail through Postman or even restarting the prod server works.
Expected Behaviour:
If some error occurs while sending the email, inside the database, the status should be changed to fail
, but it persists in sending
which is the default value of the status field.
Actual Behaviour: First, it does not update the status of the current notification, it remains in the sending state. Second, it then stops sending emails to every other email. Also, I've checked that it doesn't reach the 100 emails/per day limit set by SendGrid.
Here with I have attached the server code I am using to send mail
export async function sendGridMails({
to,
metadata,
notificationType,
...rest
}: {
to: string;
metadata: any;
notificationType: any;
_id: ObjectId;
}) {
const {
email: {
subject
},
} = metadata;
const html = templates[notificationType](metadata);
const msg = {
to,
from: config.emailSettings.email, // Use the email address or domain you verified above
subject,
html,
};
try {
console.log("sending sgmails to ", {
to,
subject
});
await sgMail.send(msg);
console.log("Mail sent ", {
to,
subject
})
await DbServices.findOneAndUpdate({
query: {
_id: rest._id
},
model: MODEL_NAMES.NOTIFICATION_MODEL,
updateParam: {
status: 'sent'
},
});
} catch (error: any) {
logger.error(`Error occured while sending mail to ${to} about ${metadata.email.subject}`);
await DbServices.findOneAndUpdate({
query: {
_id: rest._id
},
model: MODEL_NAMES.NOTIFICATION_MODEL,
updateParam: {
status: 'failed'
},
});
}
}
SendGrid says it didn't receive such mail request
DB Status
Instantiating sendgrid inside the function solved the problem for me.