Skip to content

Commit

Permalink
colors are added to logger
Browse files Browse the repository at this point in the history
  • Loading branch information
msinamsina committed Aug 6, 2023
1 parent 8f257ef commit ffeea54
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 62 deletions.
90 changes: 39 additions & 51 deletions automail/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,57 +13,63 @@
app = typer.Typer()


def run_process(pid, resume=True):
def run_process(pid, is_resume=True, wait_time=5):
"""
This function will run a process with a specific id
Parameters
----------
pid : int
the process id
resume : bool
is_resume : bool
if True, the program will resume the process if it is paused, otherwise it prints a warning message and \
return without doing anything
"""
# initialize the logger
logger = init_logger('cli')
logger.info("Reading arguments...")

# get the database session
session, engin = get_session()
create_tables(engin)

logger = init_logger('manager')
logger.info("Reading arguments...")
# get the process and check if it exists
process = session.query(Process).filter(Process.id == pid).first()
if not process:
logger.error(f"ID:{pid} => Process not found. You can see all processes with 'mailmanager list' command")
logger.error(f"ID:{pid} => Process not found. You can see all processes with 'automail list' command")
return

sender_email = process.sender
subject = process.subject
temp_file = process.temp_file
if resume:

if is_resume:
if process.status != "paused":
print(f"ID:{pid} => Program is already {process.status}")
logger.error(f"ID:{pid} => Program is already {process.status}. "
f"For resuming the program, it should be paused")
return
contacts = session.query(Record).filter(Record.process_id == pid, Record.status == "unsent").all()
else:
if process.status in ["paused", "in progress", 'finished']:
logger.warning(f"ID:{pid} => Program is already {process.status}")
print(f"ID:{pid} => Program is already {process.status}")
print(f"You can resume the program with 'mailmanager resume {pid}' command")
print(f"You can see all processes with 'mailmanager list' command")
while True:
check = input(f"Are you sure you want to sent all email again? (y/n)")
if check == "n":
return
elif check == "y":
break
else:
print("Please enter y or n!")
logger.warning(f"the `automail start {id}` command will strart the program from the beginning")

check = typer.confirm(f"Are you sure you want to start the program from the beginning?", default=False)
if not check:
logger.info(f"ID:{pid} => Program not started")
return

contacts = session.query(Record).filter(Record.process_id == pid).all()

password = typer.prompt(f"Enter password for {sender_email}", hide_input=True)
# get the password
logger.info("Creating EmailSender obj...")
if typer.confirm(f"Do you want to use the initial password for {sender_email}?", default=True):
sender = EmailSender(cfg="config.cfg", user=sender_email)
else:
password = typer.prompt(f"Enter password for {sender_email}", hide_input=True)
sender = EmailSender(cfg="config.cfg", user=sender_email, password=password)

# Create a secure SSL context
logger.info("Creating EmailSender obj...")
sender = EmailSender(cfg="config.cfg", user=sender_email, password=password)
if temp_file:
sender.set_template(temp_file)

Expand All @@ -74,24 +80,20 @@ def run_process(pid, resume=True):
for contact in contacts:
process = session.query(Process).filter(Process.id == pid).first()
if process.status == "paused":
logger.info(f"ID:{pid} => Pausing the program")
pause = True
break
logger.info(f"ID:{pid} => is paused by other process")
session.close()
engin.dispose()
return
logger.info(f"Sending email to: {contact.receiver}")
sender.send(contact.receiver, subject, contact.data)
contact.status = "sent"
session.commit()
logger.info(f"ID:{contact.id} => Email sent to {contact.receiver}")
time.sleep(10)

if not pause:
process.status = "finished"
session.commit()
logger.info(f"ID:{pid} => Program finished successfully")
time.sleep(wait_time)


session.close()
engin.dispose()
process.status = "finished"
session.commit()
logger.info(f"ID:{pid} => Program finished successfully")


def _version_callback(value: bool) -> None:
Expand Down Expand Up @@ -243,8 +245,6 @@ def register(
None,
"--template",
"-t",
# exists=True,
# file_okay= True,
help="The body of your email.",
),

Expand All @@ -266,7 +266,6 @@ def register(
typer.secho(f"File {template} does not exist. or the file type is not supported. "
f"the file type should be .txt or .html", fg=typer.colors.RED)
continue
print(title)
if not os.path.exists(title):
shutil.os.mkdir(title)
else:
Expand Down Expand Up @@ -322,7 +321,7 @@ def start(
typer.secho("Please enter the id of the process.", fg=typer.colors.RED)
raise typer.Exit(code=0)
else:
run_process(pid=id, resume=False)
run_process(pid=id, is_resume=False)


@app.command()
Expand All @@ -331,12 +330,7 @@ def resume(
None,
help="The id of the process.",
),
is_test: bool = typer.Option(
False,
"--test",
"-t",
help="Test output.",
),

) -> None:
"""Resume sending emails."""
if os.path.exists('./mail.db') and os.path.exists('./config.cfg'):
Expand All @@ -347,7 +341,7 @@ def resume(
typer.secho("Please enter the id of the process.", fg=typer.colors.RED)
raise typer.Exit(code=0)
else:
run_process(pid=id, resume=True)
run_process(pid=id, is_resume=True)


@app.command()
Expand All @@ -356,12 +350,6 @@ def stop(
None,
help="The id of the process.",
),
is_test: bool = typer.Option(
False,
"--test",
"-t",
help="Test output.",
),
) -> None:
"""Stop sending emails."""
if os.path.exists('./mail.db') and os.path.exists('./config.cfg'):
Expand Down Expand Up @@ -516,4 +504,4 @@ def list_records(
engin.dispose()

if __name__ == "__main__":
app(prog_name=__app_name__)
app(prog_name=__app_name__)
5 changes: 3 additions & 2 deletions automail/emailsender.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,12 @@ def __init__(self, user, password, host="smtp.gmail.com", port=465, is_test=Fals
self.port = port
self.password = None

print(password)
print("-" * 100)
if not self.__test_flg:
self.__logger.info("Connecting to SMTP server...")

self.password = password

self.server = smtplib.SMTP_SSL(self.host, self.port)
self.__logger.info("Connected to SMTP server.")
self.__logger.info(f"Logging in to user account: {self.user}...")
Expand Down Expand Up @@ -241,4 +242,4 @@ def send(self, receiver_email_address: str, subject: str, data: dict, attachment
except Exception as e:
self.__logger.error("Error sending email to: " + receiver_email_address + " error: " + str(e))
return {'test': self.__test_flg, 'err': str(e)}
return output
return output
19 changes: 10 additions & 9 deletions automail/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import logging
import sys
import configparser
import multiprocessing
import coloredlogs


def init_logger(name=''):
"""This function will initialize a logger object
Expand Down Expand Up @@ -43,15 +44,15 @@ def init_logger(name=''):
"""
logger_obj = logging.getLogger(name)
# logger_obj = multiprocessing.get_logger(name)
coloredlogs.install(level='DEBUG', logger=logger_obj, fmt='[%(asctime)s - %(levelname)s (%(name)s) ] : %(message)s')
logger_obj.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s - %(levelname)s (%(name)s) ] : %(message)s')
handler1 = logging.StreamHandler(sys.stdout)
handler1.setFormatter(formatter)
# handler2 = logging.FileHandler('../emailsender.log')
# handler2.setFormatter(formatter)
logger_obj.addHandler(handler1)
# logger_obj.addHandler(handler2)
# handler1 = logging.StreamHandler(sys.stdout)
# handler1.setFormatter(formatter)
handler2 = logging.FileHandler('../emailsender.log')
handler2.setFormatter(formatter)
# logger_obj.addHandler(handler1)
logger_obj.addHandler(handler2)
return logger_obj


Expand Down Expand Up @@ -148,4 +149,4 @@ def get_config_dict():
'user': config.get('account', 'user', fallback=''),
'password': config.get('account', 'password', fallback='')
}
return config_dict
return config_dict

0 comments on commit ffeea54

Please sign in to comment.