Created
July 25, 2023 02:02
-
-
Save wmakeev/2a7d79663799cbdcc64f8f59734a1b0d to your computer and use it in GitHub Desktop.
[Get email attachments with IMAP] #email #imap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { ImapFlow } from 'imapflow' | |
| import { simpleParser } from 'mailparser' | |
| import { writeFile } from 'node:fs/promises' | |
| import path from 'node:path' | |
| import { env } from './env.js' | |
| const { EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASSWORD } = env | |
| const client = new ImapFlow({ | |
| host: EMAIL_HOST, | |
| port: EMAIL_PORT, | |
| secure: true, | |
| auth: { | |
| user: EMAIL_USER, | |
| pass: EMAIL_PASSWORD | |
| }, | |
| logger: false | |
| }) | |
| // Wait until client connects and authorizes | |
| await client.connect() | |
| // Select and lock a mailbox. Throws if mailbox does not exist | |
| const lock = await client.getMailboxLock('INBOX') | |
| try { | |
| console.log('Loading messages..') | |
| while (true) { | |
| const firstMessage = await client.fetchOne('1:*', { | |
| source: true | |
| }) | |
| if (!firstMessage) { | |
| console.log('INBOX is empty') | |
| break | |
| } | |
| const parsedMessage = await simpleParser(firstMessage.source) | |
| console.log( | |
| `Message loaded - "${parsedMessage.subject}" (uid: ${firstMessage.uid})` | |
| ) | |
| for (const attachment of parsedMessage.attachments) { | |
| if (!attachment.filename) continue | |
| await writeFile( | |
| path.join(process.cwd(), '__temp/attachments', attachment.filename), | |
| attachment.content | |
| ) | |
| console.log(` attachment downloaded - ${attachment.filename}`) | |
| } | |
| const result = await client.messageDelete(String(firstMessage.uid), { | |
| uid: true | |
| }) | |
| console.log(` message deleted - ${result}`) | |
| } | |
| } finally { | |
| // Make sure lock is released, otherwise next `getMailboxLock()` never returns | |
| lock.release() | |
| } | |
| // log out and close connection | |
| await client.logout() | |
| console.log('DONE.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment