If you need deeper control or are working in an older codebase, combine node-imap with Mailparser : to the IMAP server. Fetch the message body using imap.fetch() . Stream the raw mail data into Mailparser .
const { ImapFlow } = require('imapflow'); const fs = require('fs'); async function downloadEmailAttachment() { const client = new ImapFlow({ host: 'imap.gmail.com', port: 993, secure: true, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } }); await client.connect(); let lock = await client.getMailboxLock('INBOX'); try { // Find the most recent message with an attachment for await (let message of client.fetch('1:*', { envelope: true, bodyStructure: true })) { const attachments = findAttachments(message.bodyStructure); for (let attachment of attachments) { // Download the specific part let { content } = await client.download(message.uid, attachment.part, { uid: true }); content.pipe(fs.createWriteStream(attachment.filename)); console.log(`Saved: ${attachment.filename}`); } } } finally { lock.release(); await client.logout(); } } Use code with caution. 3. Alternative: Using node-imap and Mailparser
for the attachment event in Mailparser to save the file stream directly to your local disk. 4. Security Requirements How to read and save attachments using node-imap node js download email attachment
Using ImapFlow is often the cleanest approach because it provides a direct download() method for specific message parts. javascript
: A lower-level, event-based legacy library that is very powerful but more complex to implement. If you need deeper control or are working
: Part of the Nodemailer project, it converts raw email data into structured JavaScript objects, making it easy to grab the attachments array. 2. How to Download via IMAP (ImapFlow Example)
To download email attachments in Node.js, you generally use the to access the mailbox and a parsing library like Mailparser to extract the actual files. 1. Key Libraries for the Job You will typically need a combination of two libraries: const { ImapFlow } = require('imapflow'); const fs
: A modern, easy-to-use IMAP client for Node.js that supports async/await and streaming.