'save attachment to a file using nodemailer and imap-simple
I have the following code imaps.connect(imapEmailConfig).then(function (connection) {
connection.openBox('INBOX').then(function () {
const searchCriteria = [
// "UNSEEN",
'1:50']
var fetchOptions = { bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'], struct: true };
// retrieve only the headers of the messages
return connection.search(searchCriteria, fetchOptions);
}).then(function (messages) {
var attachments = [];
messages.forEach(function (message) {
var parts = imaps.getParts(message.attributes.struct);
attachments = attachments.concat(parts.filter(function (part) {
return part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT';
}).map(function (part) {
// retrieve the attachments only of the messages with attachments
return connection.getPartData(message, part)
.then(function (partData) {
return {
filename: part.disposition.params.filename,
data: partData
};
});
}));
});
return Promise.all(attachments);
}).then(function (attachments) {
console.log(attachments); // output is stated under the code
// =>
// [ { filename: 'cats.jpg', data: Buffer() },
// { filename: 'pay-stub.pdf', data: Buffer() } ]
for (const attachment in attachments) {
try {
fs.writeFile(`${attachment.filename}`, Buffer.from(attachment.data, 'base64'))
}
catch (error){
console.error(error)
}
}
});
the code yield an error that says
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
the output of the console.log(attachment)
{
filename: '5783482.pdf',
data: <Buffer 25 50 44 46 2d 31 2e 37 0a 25 e2 e3 cf d3 0a 31 31 20 30 20 6f 62 6a 0a 3c 3c 2f 46 69 6c 74 65 72 2f 46 6c 61 74 65 44 65 63 6f 64 65 2f 4c 65 6e 67 ... 67036 more bytes>
}
I have used the following library's 'imap-simple', 'mailparser') and 'fs'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
