如何替换 MIME 消息中的 body 文本?

How to replace body text in MIME message?

我正在尝试向各种用户发送一封自动电子邮件,其中包含他们订阅的湖的变化:

message = MIMEMultipart()
message['From'] = email  # Sender
message['Subject'] = "Algae Bloom Alert\n"  # Subject

for user in subscriber_dict:
    sms_gateway = subscriber_dict[user]['email']
    message['To'] = subscriber_dict[user]['email']
    body = (
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    message.attach(MIMEText(body, 'plain'))  # Attaching body to email
    sms = message.as_string()
    server.sendmail(email, sms_gateway, sms)
        
    # Reset body here ideally

    print(f"Email sent at {formatted_time}")

但是,当发送电子邮件时,每封连续的电子邮件都包含前一封电子邮件的内容。有谁知道我如何重置 body 以便我不依附于以前的主体而是编写新的主体?

没错 - 没有必要继续深入研究 subscriber_dict。而不是:

for user in subscriber_dict:
    sms_gateway = subscriber_dict[user]['email']

你可以这样做:

for user in subscriber_dict.values():
    sms_gateway = user['email']

您的 for 循环重复使用相同的 message。它可能应该在每个循环中创建一个新的:

FROM_ADDR = "jake@lakefacts.gov.au"

for user in subscriber_dict.values():
    message = MIMEMultipart()
    message['From'] = FROM_ADDR
    message['To'] = user['email']
    message['Subject'] = "Algae Bloom Alert\n"
    body = (
        f"This is an algae alert for Lake {user['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    message.attach(MIMEText(body, 'plain'))
    sms_gateway = user['email']
    sms = message.as_string()
    server.sendmail(email, sms_gateway, sms)
    print(f"Email sent at {formatted_time}")

不要重复使用相同的 message。在循环内创建一个新的。

您的代码似乎是为 Python 3.5 或更早版本编写的。 email 库在 3.6 中进行了大修,现在更加通用和合乎逻辑。可能会扔掉你所有的东西,然后从 examples from the email documentation.

重新开始
from email.message import EmailMessage
...

for user in subscriber_dict:
    message = EmailMessage()
    message['From'] = email
    message['Subject'] = "Algae Bloom Alert"  # no \n
    message['To'] = subscriber_dict[user]['email']
    message.set_content(
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    server.send_message(message)

    print(f"Email sent at {formatted_time}")

您可能希望避免调用发送方变量 email 以避免隐藏 email 库,尽管在本示例中这并不重要。

有了 .set_content(),您实际上可以一遍又一遍地重复使用相同的 message,但是这样做并没有实际的好处,如果您错误地替换了较早消息的某些部分,则会出现问题可能是丑陋的。 (例如,打字错误可能会导致您向同一收件人发送的次数与您的用户数一样多!)