- Saved searches
- Use saved searches to filter your results more quickly
- License
- ManuelLR/Notmail_Bot
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Email — Telegram Python Bot
- Problem Statement
- Pseudo-Code
- Code
- Connecting to the email Server
- Reading emails
- Extract the important parts from the message
- Sending the message to Telegram
- Finally
- One more thing
- Results
- Saved searches
- Use saved searches to filter your results more quickly
- License
- geeksLabTech/email-client
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- readme.md
- About
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Telegram bot that acts as an email client
License
ManuelLR/Notmail_Bot
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Telegram bot that acts as an email client.
- Auto check email account and notify news.
- Friendly interface.
- Multiple email accounts.
- Compatible with IMAP protocol. (More in the future).
- Read email on Telegram, mark as read/unread, archive/delete and much more.
First of all, we need to know our username and the bot_token . The username could be configure in your Telegram app settings (also known as alias ). To get the bot_token is necessary to speak with the @BotFather and introduce the /newbot command. It will ask all necesary data and finally, it will give to you the bot_token also called API Token .
We can launch in several ways:
To use docker-compose you need to install on your computer Docker-CE and Docker-compose.
Before running it you need to enter the variables in the new file called .env .
cp .example.env .env nano .env
Finally, we execute the next command and can start to talk with the bot:
If we update the code, you only need to update it ( git pull ) and relaunch docker compose with the following command:
git pull docker-compose up -d --build
sudo docker build -t notmail_bot . sudo docker run -d --name Notmail_bot \ --restart always \ --env-file .env \ manuellr/notmail_bot
pip install -r requirements.txt python notmail_bot.py --config_path my-config/my_config.ini
You can consult the contributors in the AUTHORS file or see the contributors of a specific file executing the next script:
git blame -C -C -M -- FILE_TO_CONSULT | \ sed -e 's/[^(]*(\([^0-9]*\).*/\1/' -e 's/[\t ]*$//' | \ sort | uniq -c | sort -nr
About
Telegram bot that acts as an email client
Email — Telegram Python Bot
As a a cyber security architect, I am often responsible for some critical security infrastructure, whose uptime is, well, you guessed it, paramount. Usually, these systems have some sort of warning bells when hell breaks loose, and this can be in the form of email alerts, or monitoring dashboards.
I wrote this script to avoid checking emails on weekends. You probably also, don’t want to go back to work on Monday, to find your infrastructure went off on Friday evening, and no one was there to give it CPR.
Since I am always on my phone, I wanted an easier, less stressful way to receive high priority alerts.
Problem Statement
I was responsible for a system that generated such email alerts as below, sometimes in thousands:
Event Type: Gateway state change Time: 8/4/20 11:04 PM Subsystem: Gateway Severity: High Message: The status of the gateway SERVER1-GW-01 is Disconnected. Please check the gateways section of the user interface for additional information. Reporting Component Name: SERVER1-GW-01 Reporting Component IP: X.X.X.X
I wanted to filter from the thousands of similar alerts, get the Critical severity ones (usually pointing to a downtime) in a stripped-down format, sent to my phone.
Pseudo-Code
Scan an email folder for unread emails
Parse the emails and extract the content
Find the most important parts of the message
Send the information as a Telegram alert
I found a fantastic blog on repl which helped me quickly cover some bits of the task.
Code
The complete code is available on my Github Page. I have explained the important bits below.
Connecting to the email Server
In this code, I will be using Outlook as the email server. We will use the imapclient python library to connect to the outlook server. The imapclient library implements a method that takes the username and email and connects to the email server.
print("Initializing IMAP . ", end="") global connect connect = imapclient.IMAPClient(imap_server) connect.login(read_from, password) connect.select_folder("INBOX", readonly=False) print("Success")
readonly=False ensures the emails are marked as read. This avoids duplicates.
Reading emails
Unread emails are returned as UIDs . The UIDs are what we use to fetch actual emails.
//Code that checks for unread emails uids=i.search(['UNSEEN']) if not uids: return None else: print("Found %s unread emails" %len(uids)) return i.fetch(uids, ['BODY[]', 'FLAGS'])
Next we analyze and return the actual message. pyzmail module can help us extract the sender, subject, and message. It is important to only analyze messages from the particular sender, to avoid another system or user sending a conflicting email. Also, since I am only interested in the high severity events, I will ignore any emails with a medium or low severity in the subject.
1 2 3 4 5 6 7 8 9 10 11 12
message=pyzmail.PyzMessage.factory(raws[a][b'BODY[]']) global subject subject=msg.get_subject() from=msg.get_address('from') if frm[1] != sender_address: print("Unread is from %s skipping" %(frm[0][0], frm[0][1])) return None if msg.text_part is None: print("No message to parse") return None if "High Severity" not in subject: return None
Extract the important parts from the message
Using regex, we can analyze the message returned and extract the information, from the data.
Message: The status of the gateway SERVER1-GW-01 is Disconnected. Please check the gateways section of the user interface for additional information.
For a telegram message, we can send SERVER1-GW-01 is Disconnected , which is short, and most importantly sweet.
The regex code below does just that.
def get_event(raw_msg): pattern = re.compile(r'(\bMessage:)([a-zA-Z0-9-\s]+(\bgateway)([a-zA-Z0-9-\s]+.))', re.I) matches = pattern.finditer(raw_msg) return matches
Sending the message to Telegram
To send messages to Telegram, we need a bot and a channel . The bot needs to be an administrator on the channel. Create a Bot with BotFather and note the bot token . Then create a public channel and add the bot as an administrator.
To get the channel ID (which we will use as the chat ID), post the URL below on your browser, replacing the bot_token with your bot token.
https://api.telegram.org/bot/getupdates
Then post a random message on the channel and reload the link. You will see the chat ID as
We can then we use the sendMessage method to send the alert to Telegram.
def botsy(bot_token, chat_id, telegram_message): bot = telegram.Bot(bot_token) bot.sendMessage(chat_ID, text=telegram_message)
Finally
Finally, we loop through methods created to monitor for new emails, analyze them, pass them through a regex function to get the required message and send it to Telegram. Then keep waiting for new messages/alerts to arrive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
while True: try: messages=get_unread() while messages is None: time.sleep(check_freq) messages = get_unread() for a in messages.keys(): if type(a) is not int: continue received_email=analyze_msg(messages, a) if received_email is None: pass elif received_email: parsed_email = get_event(received_email) for match in parsed_email: if not match.group(4): # print(match.group(4)) pass elif match.group(4): botsy(str(match.group(4))) break else: pass
The loop checks for any unread messages and checks whether the sender is from the system we want to monitor. If there are no messages, it sleeps for a defined time interval and rechecks. If a message is received, it is analyzed, and the body part extracted which is then checked by the regex function to determine if it contains the required message that warrants a notification on Telegram. If such an alert exists, it is sent Telegram. The match.group only checks the fourth item returned from the regex function, since it is the important bit that we care for. This area requires customization to suit your own needs.
One more thing
We create a config file to carry the different variables defined on the code. Which is then imported to the code.
The code gets the mailbox to read emails from and its associated imap server, the password using the getpass library which will hide the password when it’s being typed.
import getpass read_from=input("Enter mailbox to read from: ") imap_server=input("Enter imap server: ") paswd=getpass.getpass("Account Password: ") sender_address =input("Enter the trusted system email sender address: ") bot_token = input("bot token : ") chat_ID = input ("chat id : ")
Results
When one of the servers experiences a fault and goes offline, we get a server disconnected alert on telegram and when it gets online, an uptime alert is sent.
Notifications sent to Telegram
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Telegram Bot to Use any imap/smtp email account
License
geeksLabTech/email-client
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
readme.md
python email client for any email server that supports imap and smtp,
using a telegram bot as interface
Installation and Deployment
Manual Install and Deploy
First of all make sure that your system is up to Date
(Ubuntu) sudo apt-get update && sudo apt-get upgrade
Install Mongodb for users handle (Ubuntu) sudo apt-get install mongodb
(Arch) sudo pacman -S mongodb
Set MongoDB daemon to run at startup:
sudo systemctl enable mongod sudo systemctl start mongod
Then make sure that python3 is installed and in the latest version (3.8 at the time of writting) (Ubuntu) sudo apt-get install python3
(Arch) sudo pacman -S python3
Now install pip (Ubuntu) python3 -m pip install —upgrade pip
And then install the requirements
pip install -r requirements.txt
Now you are Ready to Deploy
Email Servers Configuration
Finally to set up the bot and the server run:
now you would be asked to input the bot token, name and url
pyhton3 main.py setup_email
now you would be asked to input the email imap host and port as well as the smtp host and port now you are ready to use the service
Generate encryption key for the database, its very important that you keep this, if this key gets lost you wont be able to decrypt the data
pyhton3 main.py setup_key
python3 main.py recieve your.email@estudiantes.matcom.uh.cu yourpassword
python3 main.py send your.email@estudiantes.matcom.uh.cu yourpassword reciever@example.com subject body
and for a specific command help type:
You can access our telegram bot at @experimental_email_bot (temporary name) on telegram
in order to use the bot you need to register on the db, to do it, sent the bot the following info:
/register this will register email and password encripted on the db
to recieve unread emails just type:
/recieve
Loguot and remove your data from the server /logout
About
Telegram Bot to Use any imap/smtp email account