【问题标题】:How can I use a non-zero returncode to send email to a backup address using smtplib?如何使用非零返回码将电子邮件发送到使用 smtplib 的备份地址?
【发布时间】:2023-04-10 20:39:02
【问题描述】:

我正在 Python3 中试验smtplib。 我想将变量的内容发送到电子邮件地址。如果有smtplib.SMTPAuthenticationError,我想将该变量发送到另一个电子邮件地址。这有效(见下面的代码)。但是如果我想添加第三个电子邮件地址(如果前两个由于某种原因失败)怎么办? 我不认为tryexcept 允许我添加另一个相同代码块(具有不同的电子邮件登录详细信息)。 我知道使用subprocess,可以获取变量的returncode,然后使用if。 例如:

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

如果不使用subprocess,我不知道如何做到这一点。有人可以请教吗? 代码如下:

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

【问题讨论】:

标签: python python-3.x smtplib return-code


【解决方案1】:

如果邮件较多,可以使用下面的sn-p

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 2016-11-04
    • 2014-04-27
    • 2014-07-13
    • 2011-09-17
    • 2021-10-09
    • 2019-12-04
    • 2012-09-11
    相关资源
    最近更新 更多