根据我是按语句还是作为块运行代码语句,如何获得不同的结果?

时间:2019-03-07 15:06:16

标签: python quotes smtplib

我有一个用于在符合条件的情况下发送电子邮件的代码:

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

但是,如果我运行整个代码,则发送的电子邮件的主题为空,正文为空,所有内容都放置在电子邮件的“发件人”中。

如果我按语句运行语句(在条件语句之后开始),则可以正确接收电子邮件。我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

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

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

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