Reputation: 123
Hi there i'm trying to use tenacity for sending an email, the script is the following:
from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP
@retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):
try:
#ENVIO DE DATOS
#Lista de mails a enviar la info
mails_to = mails_to_list
msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))
for table in tables:
msg = msg + table + "\r\n\r\n"
print(msg)
with SMTP(host = smtp_host, port = smtp_port) as smtp:
smtp.starttls()
smtp.login(user = smtp_user, password = smtp_pass)
smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
smtp.quit()
except Exception:
print(Exception)
The thing is that if i run email_tables(vars)
the output runs only once the method and then exits the script.
If i remove the try-except sentence and don't print the Exception the script runs 7 times as expected and then raises the error.
I don't know what i'm doing wrong here in order for retry to work. Later i would like to save a log in a file when exception is raised, ideally with how many times it failed.
Thanks in advance
Upvotes: 1
Views: 1220
Reputation: 123
Seems that all i needed to do is add a raise sentence with the exception for retry to be able to read it. Final code:
from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP
@retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):
try:
#ENVIO DE DATOS
#Lista de mails a enviar la info
mails_to = mails_to_list
msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))
for table in tables:
msg = msg + table + "\r\n\r\n"
print(msg)
with SMTP(host = smtp_host, port = smtp_port) as smtp:
smtp.starttls()
smtp.login(user = smtp_user, password = smtp_pass)
smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
smtp.quit()
except Exception:
print(Exception)
raise(Exception)
Upvotes: 0