Retrying in Python

less than 1 minute read

Recently, I was writing some Python code to send emails and the connection to the SMTP server was randomly failing. Luckily I found tenacity and I fixed this issue in no time.

tenacity provides an easy way to retry when executing unreliable functions like the case above. There are so many examples to choose from based on the situation and in my case here’s what I ended up doing.

from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
from smtplib import SMTPServerDisconnected

@retry(retry=retry_if_exception_type(SMTPServerDisconnected), wait=wait_fixed(5), stop=stop_after_attempt(5))
def send_email():

Whenever the email couldn’t be sent due to a SMTPServerDisconnected exception, I retry sending the same email until successful every five seconds but not more than five times.

Leave a Comment