const chalk = require('chalk'); const {ImapFlow} = require('imapflow'); const simpleParser = require('mailparser').simpleParser const {Telegraf} = require('telegraf'); require('dotenv').config() const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN); const POLLING_TIMEOUT = process.env.POLLING_TIMEOUT const MARK_STRING = process.env.MARK_STRING const clientConfig = { host: process.env.EMAIL_IMAP_SERVER, port: process.env.EMAIL_IMAP_SERVER_PORT, secure: true, auth: { user: process.env.EMAIL_ADDRESS, pass: process.env.EMAIL_PASSWORD, } } const main = async () => { const client = new ImapFlow(clientConfig); await client.connect(); // Wait until client connects and authorizes const lock = await client.getMailboxLock('INBOX'); // Open mailbox try { let listSeenMsgId = await client.search({seen: false}); // search only unseen messages console.log('๐Ÿ“Œ', chalk.cyan('UNSEEN LIST:'), listSeenMsgId) for await (let message of client.fetch(listSeenMsgId, { envelope: true, source: true })) { if (message.envelope.subject.includes(MARK_STRING)) { let email = Buffer.from(message.source).toString() const parsed = await simpleParser(email) console.log('๐Ÿ“Œ', chalk.cyan('Message:'), chalk.yellow(parsed.text)); if (parsed.text) { bot.telegram.sendMessage(process.env.TELEGRAM_GROUP_ID, parsed.text) .then() .catch(console.error) } client.messageFlagsAdd(message.seq.toString(), ['\\Seen']) .then((result: any) => console.log('๐Ÿ“Œ', chalk.cyan(`Set seen flag for id-${message.seq}`), result)) .catch(console.error) } } } catch (e) { console.log(e) } finally { lock.release(); // mandatory release mailbox await client.logout(); // log out and close connection console.log('๐Ÿงก', chalk.cyan('Heartbeat is ok')) } }; //main().then().catch(err => console.error(err)); // start once for development setInterval(async () => { main().then().catch(console.error); }, Number(POLLING_TIMEOUT) * 1000)