1

您好我正在尝试使用坚韧来发送电子邮件,脚本如下:

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)

问题是,如果我运行email_tables(vars)输出只运行一次该方法,然后退出脚本。

如果我删除 try-except 语句并且不打印异常,则脚本按预期运行 7 次,然后引发错误。

我不知道我在这里做错了什么才能重试工作。稍后我想在引发异常时将日志保存在文件中,理想情况下它失败了多少次。

提前致谢

4

1 回答 1

0

似乎我需要做的就是添加一个提升语句,但重试能够阅读它。最终代码:

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)
于 2020-09-25T19:44:07.623 回答