Skip to content

Instantly share code, notes, and snippets.

@ivanfgm
Last active January 13, 2023 10:46
Show Gist options
  • Save ivanfgm/dce0495f0ee00b064616958e450d05bd to your computer and use it in GitHub Desktop.
Save ivanfgm/dce0495f0ee00b064616958e450d05bd to your computer and use it in GitHub Desktop.
Small script to send received emails to a telegram bot, easy piece thanks to: node-telegram-bot-api and mail-listener2
const makeBot = require('node-telegram-bot-api');
const mailListener = require("mail-listener2");
const config = {
// First get your telegram bot
telegramToken: 'Obtain your token talking to BotFather on telegram',
// Send a message to the bot and paste here your chat id (the response)
// TODO: login to avoid this step and allow multiple users
chatID = 'Chat ID',
// Gmail or Gsuite settings
email: "gmail or gsuite email here",
email_pass: "email password here"
};
const bot = new makeBot(config.telegramToken, { polling: true });
bot.on('message', msg => bot.sendMessage(chatId, msg.chat.id));
var mailInbox = new mailListener({
username: config.email,
password: config.email_pass,
host: "imap.gmail.com",
port: 993,
tls: true,
markSeen: true,
fetchUnreadOnStart: true,
});
mailInbox.start(); // start listening
mailInbox.on("server:connected", function () {
console.log("imapConnected");
});
mailInbox.on("server:disconnected", function () {
console.log("imapDisconnected");
throw new Error('Restart app due to IMAP disconnection');
});
mailInbox.on("error", function (err){
console.log(err);
});
mailInbox.on("mail", function (mail, seqno, attributes){
bot.sendMessage(config.chatID, `
<b>${mail.subject}</b>
${mail.text}
`, {
parse_mode: 'HTML'
});
});
@ivanfgm
Copy link
Author

ivanfgm commented Aug 26, 2019

The script is made to be run by a supervisor, the client disconnects sometimes so the script dies to let the supervisor restart him and restart the connection. A good one is https://github.com/foreversd/forever

@ivanfgm
Copy link
Author

ivanfgm commented Aug 26, 2019

Dependencies install:

yarn init && yarn add node-telegram-bot-api mail-listener2

@shelomito12
Copy link

Does this still work? Providing a password from your gmail account is the only way for this work properly? Can you have like a specific app password for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment