How can I use a non-zero returncode to send email to a backup address using smtplib?

75 Views Asked by At

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()
1

There are 1 best solutions below

0
kosciej16 On

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