1

I am experimenting with smtplib in Python3. I want to send the content of a variable to an email address. If there is an smtplib.SMTPAuthenticationError, I want to send that variable to an alternative email address. This works (see code below). But what if I want to add a third email address (if the first two fail for some reason)? I don't think try and except allow me to add another block of the same code (with different email login details). I know with subprocess, it's possible to acquire the returncode of a variable and then use if. For example:

result = subprocess.run(["ls", "-al"], capture_output = True)
if result !=0:
    do_something_to_list_the_directory

I don't know how this can be done without using subprocess. Can anyone please advise? Code below:

try:
    mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
    mail_sending_attempt.starttls()
    mail_sending_attempt.login(send, passinfo)    ### this will not work
    mail_sending_attempt.sendmail(send, receive, message)
    mail_sending_attempt.quit() 
    
except Exception:
    mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
    mail_sending_attempt.starttls()
    mail_sending_attempt.login(send2, passinfo2)    ### this will not work
    mail_sending_attempt.sendmail(send2, receive2, message)
    mail_sending_attempt.quit()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
dippy-dont
  • 11
  • 1
  • 1
    Why not use a nested `try`-`except` within the first `except` block? See this question: https://stackoverflow.com/questions/17015230/are-nested-try-except-blocks-in-python-a-good-programming-practice – Arne Dec 20 '21 at 22:29

1 Answers1

0

In case there are more email, you can use following snippet

from dataclasses import dataclass

@dataclass
class EmailData:
    send: str
    passinfo: str
    receive: str


main = EmailData("send1", "passinfo1", "receive1")
backup_1 = EmailData("send2", "passinfo2", "receive2")
...

for data in [main, backup_1, ...]:
    try:
        mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
        mail_sending_attempt.starttls()
        mail_sending_attempt.login(data.send, data.passinfo)
        mail_sending_attempt.sendmail(data.send, data.receive, message)
        mail_sending_attempt.quit()
        break
    except Exception:
        continue
else:
    # the case when we won't encounter break, so every login failed.
    raise Exception
kosciej16
  • 6,294
  • 1
  • 18
  • 29