From da79194e87ae9c928ecf0b42f2a2a69a13256b64 Mon Sep 17 00:00:00 2001 From: Alexander Hosking Date: Sun, 8 Jan 2023 10:11:40 -0500 Subject: [PATCH] Update for multiple accounts --- gmail/email_count.py | 55 ++++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/gmail/email_count.py b/gmail/email_count.py index b2880d0..5e05ed0 100644 --- a/gmail/email_count.py +++ b/gmail/email_count.py @@ -1,37 +1,42 @@ import os import imaplib -import time -import re +import json from dotenv import load_dotenv load_dotenv() -print(os.environ.get("APP_PASSWORD")) +EMAIL_ACCOUNTS = json.loads(os.environ.get("MAIL_ACCOUNTS")) +EMAIL_PASSWORDS = json.loads(os.environ.get("MAIL_PASSWORDS")) +# using zip() +# to convert lists to dictionary +accounts = dict(zip(EMAIL_ACCOUNTS, EMAIL_PASSWORDS)) +print(accounts) ################ IMAP SSL ############################## -with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl: - print("Connection Object : {}".format(imap_ssl)) - print("Logging into mailbox...") - try: - resp_code, response = imap_ssl.login("alexander@ahosking.com", os.environ.get("APP_PASSWORD")) - except Exception as e: - print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) - resp_code, response = None, None +for account in accounts: + with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl: + print("Connection Object : {}".format(imap_ssl)) + print("Logging into mailbox...") + try: + resp_code, response = imap_ssl.login(account, accounts[account]) + except Exception as e: + print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) + resp_code, response = None, None - print("Response Code : {}".format(resp_code)) - print("Response : {}\n".format(response[0].decode())) + print("Response Code : {}".format(resp_code)) + print("Response : {}\n".format(response[0].decode())) - imap_ssl.select('inbox') - resp_code, messages = imap_ssl.search(None, 'UnSeen') - if resp_code == 'OK': - if len(messages[0].split()) > 0: - print('True') - print(messages[0].split()) - print(len(messages[0].split())) - else: - print('False') + imap_ssl.select('inbox') + resp_code, messages = imap_ssl.search(None, 'UnSeen') + if resp_code == 'OK': + if len(messages[0].split()) > 0: + print('True') + print(messages[0].split()) + print(len(messages[0].split())) + else: + print('False') -############### Logout of Mailbox ###################### - print("\nLogging Out....") + ############### Logout of Mailbox ###################### + print("\nLogging Out....") - imap_ssl.close() \ No newline at end of file + imap_ssl.close() \ No newline at end of file