In our application we are attaching PDF, at some random scenario the attachment is getting corrupted. So we decided to check if the attachment size is same as before and after the attachment is attached, and validate for the same.
I couldn’t find any information regarding how the messageSize is calculated or a way to know the attachment size from the callback of transporter.sendMail().
We observed the changes in size by manipulating the attributes does not have any repeatable patter that we can take advantage off.
var mailOptions = {
from: "<some email>",
to: "<some email>",
subject: "S",
text: "",
attachments: [
{
filename: "a.pdf",
path: "./sample.pdf",
},
],
};
const getFileSize = () => {
const fileSize = fs.statSync(mailOptions.attachments[0].path);
return fileSize.size;
};
const calTotalSize = () => {
let total = 165;
if (mailOptions?.from?.length > 0) {
total = total + mailOptions.from.length;
}
if (mailOptions?.to?.length > 0) {
total = total + mailOptions.to.length;
}
if (mailOptions?.subject?.length > 0) {
total = total + mailOptions.subject.length + 11;
}
if (mailOptions?.text?.length > 0) {
total = total + mailOptions.text.length + 50;
}
if (mailOptions?.attachments?.length > 0) {
if (mailOptions.attachments?.filename?.length > 0) {
total = total + mailOptions.attachments[0].filename.length;
}
if (mailOptions.attachments?.path?.length > 0) {
total = total + mailOptions.attachments[0].path.length;
}
total = total + getFileSize();
}
return total;
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log(getFileSize(), "calculate original pdf size");
console.log(calTotalSize(), "calculate total size");
console.log(info.messageSize, "Email size");
}
});
Thank you.