根据我 运行 逐条语句还是作为块的代码,我怎么可能得到不同的结果?

How is it possible that I get different results depending on if I run the code statement by statement or as a block?

我有一个代码,用于在符合条件时发送电子邮件:

import datetime
import smtplib

today = datetime.date.today()
email_date = today
items = [1, 2]
gmail_email = "put_your_email_here"
password = "put your password here"

if email_date == today:
    # send email
    sent_from = gmail_email
    sent_to = ['email_1', 'email_2']
    sent_subject = 'Subject of the email'
    sent_body = ("""Hello,

    This is part of a reproducible code

    Kind regards""")

    email_text = """\
    From: %s
    To: %s
    Subject: %s

    %s
    """ % (sent_from, ', '.join(sent_to), sent_subject, sent_body)

    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_email, password)
    server.sendmail(sent_from, sent_to, email_text)
    server.close()

但是,如果我 运行 整个代码,发送的电子邮件主题和正文都是空的,所有内容都放在电子邮件的 "from" 中。

如果我 运行 逐条声明(在条件之后开始),我会正确收到电子邮件。我在这里错过了什么?

这可能与您将文本块分配给 email_text 变量的方式有关。文本是缩进的,而电子邮件的行首应该有 header 字段。尝试将其更改为:

        email_text = """\
From: %s
To: %s
Subject: %s

%s
""" %(sent_from, ', '.join(sent_to), sent_subject, sent_body)