-
-
Notifications
You must be signed in to change notification settings - Fork 273
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Dmitriy
committed
Nov 26, 2023
1 parent
4a80751
commit c2acfdd
Showing
9 changed files
with
189 additions
and
77 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
EMAIL= | ||
PASSWORD= | ||
MAX_MSG_COUNT= | ||
MAX_BODY_LENGTH= | ||
|
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.venv | ||
.env |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,25 @@ | ||
#!/usr/bin/python | ||
|
||
import imaplib | ||
import re | ||
from dotenv import load_dotenv | ||
from pathlib import Path | ||
import os | ||
path_to_env = Path(__file__).parent / '.env' | ||
load_dotenv(path_to_env) | ||
EMAIL = os.getenv("EMAIL") | ||
PASSWORD = os.getenv("PASSWORD") | ||
if not EMAIL or not PASSWORD: | ||
print("ERROR:Email or password not set in .env file.") | ||
exit(0) | ||
|
||
|
||
M=imaplib.IMAP4_SSL("mail.teenagemutantninjaturtles.com", 993) | ||
M.login("mickey@tmnt.com","cowabunga") | ||
M = imaplib.IMAP4_SSL("imap.gmail.com", 993) | ||
M.login(EMAIL, PASSWORD) | ||
|
||
status, counts = M.status("INBOX","(MESSAGES UNSEEN)") | ||
status, counts = M.status("INBOX", "(MESSAGES UNSEEN)") | ||
|
||
if status == "OK": | ||
unread = re.search(r'UNSEEN\s(\d+)', counts[0].decode('utf-8')).group(1) | ||
unread = re.search(r"UNSEEN\s(\d+)", counts[0].decode("utf-8")).group(1) | ||
else: | ||
unread = "N/A" | ||
unread = "N/A" | ||
|
||
print(unread) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,115 @@ | ||
#!/usr/bin/python | ||
|
||
import imaplib | ||
import email | ||
import datetime | ||
|
||
def process_mailbox(M): | ||
rv, data = M.search(None, "(UNSEEN)") | ||
if rv != 'OK': | ||
print "No messages found!" | ||
return | ||
|
||
for num in data[0].split(): | ||
rv, data = M.fetch(num, '(BODY.PEEK[])') | ||
if rv != 'OK': | ||
print "ERROR getting message", num | ||
return | ||
msg = email.message_from_bytes(data[0][1]) | ||
for header in [ 'From', 'Subject', 'Date' ]: | ||
hdr = email.header.make_header(email.header.decode_header(msg[header])) | ||
if header == 'Date': | ||
date_tuple = email.utils.parsedate_tz(str(hdr)) | ||
if date_tuple: | ||
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple)) | ||
print("{}: {}".format(header, local_date.strftime("%a, %d %b %Y %H:%M:%S"))) | ||
import html2text | ||
import re | ||
from email.header import make_header, decode_header | ||
from pathlib import Path | ||
import os | ||
from dotenv import load_dotenv | ||
|
||
path_to_env = Path(__file__).parent / '.env' | ||
load_dotenv(path_to_env) | ||
EMAIL = os.getenv("EMAIL") | ||
PASSWORD = os.getenv("PASSWORD") | ||
|
||
MAX_MSG_COUNT = int(os.getenv("MAX_MSG_COUNT", 5)) | ||
MAX_BODY_LENGTH = int(os.getenv("MAX_BODY_LENGTH", 100)) | ||
|
||
GREEN = "\033[1;32m" | ||
END_COLOR = "\033[0m" | ||
|
||
UNSEEN_FLAG = "(UNSEEN)" | ||
BODY_PEEK_FLAG = "(BODY.PEEK[])" | ||
def colorful_text(text, color): | ||
""" | ||
Function to format text with Pango markup for color. | ||
""" | ||
return f"<span foreground='{color}'>{text}</span>" | ||
|
||
def format_body(body, max_length=MAX_BODY_LENGTH): | ||
body = body.decode("utf-8", errors="ignore") | ||
|
||
if "DOCTYPE" in body: | ||
body = html2text.html2text(body) | ||
body = body.replace("\n", "").replace("\r\n", "").replace(" ", "") | ||
body = re.sub(r"\[.*\]\(.*\)", "", body) | ||
|
||
return body if len(body) < max_length else body[:max_length] + "..." | ||
|
||
def get_short_email_str(M, num_emails=MAX_MSG_COUNT): | ||
rv, data = M.search(None, UNSEEN_FLAG) | ||
email_list = list(reversed(data[0].split()))[:num_emails] | ||
|
||
for num in email_list: | ||
try: | ||
rv, data = M.fetch(num, BODY_PEEK_FLAG) | ||
if rv != "OK": | ||
print("ERROR getting message", num) | ||
continue | ||
|
||
msg = email.message_from_bytes(data[0][1]) | ||
|
||
sender = make_header(decode_header(msg["From"])) | ||
subject = make_header(decode_header(msg["Subject"])) | ||
date = make_header(decode_header(msg["Date"])) | ||
|
||
email_info = ( | ||
f"From: {colorful_text(str(sender).replace('<', '').replace('>', ''), 'green')}\n" | ||
f"Subject: {colorful_text(str(subject), 'red')}\n" | ||
f"Date: {date}\n" | ||
) | ||
|
||
if msg.is_multipart(): | ||
for part in msg.walk(): | ||
content_type = part.get_content_type() | ||
content_disposition = str(part.get("Content-Disposition")) | ||
|
||
if ( | ||
content_type == "text/plain" | ||
and "attachment" not in content_disposition | ||
): | ||
body = part.get_payload(decode=True) | ||
email_info += format_body(body) | ||
break | ||
elif ( | ||
content_type == "text/html" | ||
and "attachment" not in content_disposition | ||
): | ||
body = part.get_payload(decode=True) | ||
body = html2text.html2text( | ||
body.decode("utf-8", errors="ignore") | ||
) | ||
email_info += format_body(body) | ||
break | ||
else: | ||
print('{}: {}'.format(header, hdr)) | ||
# with code below you can process text of email | ||
# if msg.is_multipart(): | ||
# for payload in msg.get_payload(): | ||
# if payload.get_content_maintype() == 'text': | ||
# print payload.get_payload() | ||
# else: | ||
# print msg.get_payload() | ||
|
||
|
||
M=imaplib.IMAP4_SSL("mail.teenagemutantninjaturtles.com", 993) | ||
M.login("mickey@tmnt.com","cowabunga") | ||
|
||
rv, data = M.select("INBOX") | ||
if rv == 'OK': | ||
process_mailbox(M) | ||
M.close() | ||
M.logout() | ||
body = msg.get_payload(decode=True) | ||
email_info += format_body(body) | ||
|
||
email_info += "\n" + "=" * 50 + "\n" | ||
yield email_info | ||
|
||
except Exception: | ||
print("ERROR processing message: ", num) | ||
|
||
if __name__ == "__main__": | ||
# Example usage: | ||
# read_unread_emails.py | ||
import time | ||
start = time.time() | ||
|
||
M = imaplib.IMAP4_SSL("imap.gmail.com", 993) | ||
try: | ||
M.login(EMAIL, PASSWORD) | ||
rv, data = M.select("INBOX") | ||
|
||
if rv == "OK": | ||
for email_str in get_short_email_str(M, MAX_MSG_COUNT): | ||
print(email_str) | ||
else: | ||
print("Error selecting INBOX") | ||
except Exception: | ||
print("Error logging in: ", EMAIL) | ||
finally: | ||
M.logout() | ||
|
||
print(f"Time taken: {time.time() - start:.2f} seconds") |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
html2text==2020.1.16 | ||
python-dotenv==1.0.0 |