0

我对一个非常简单的 python 电子邮件脚本有一个奇怪的问题。脚本本身工作正常,但是当我在现有代码中(在 if 语句中)使用脚本时,它似乎将 FROM、TO、SUBJECT 和 TEXT 字段放在电子邮件正文中(不仅仅是 TEXT 字段)

剧本

import smtplib
SERVER = "localhost"
FROM = "test@test.com"
TO = ["myemail@email.com"] # must be a list
SUBJECT = "Test"
TEXT = "This message was sent with Python's smtplib."

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

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

当我将它包裹在 If 语句中时,它会变得混乱并将所有内容都放入电子邮件正文中。

if X == 1:
    import smtplib
    SERVER = "localhost"
    FROM = "test@test.com"
    TO = ["myemail@email.com"] # must be a list
    SUBJECT = "Test"
    TEXT = "This message was sent with Python's smtplib."

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

    %s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()
else:
    continue

这将给我一封电子邮件,如下所示

From - test@test.com
Subject -
To - undisclosed-recipients

    From: test@test.com
    To: myemail@email.com
    Subject: Hello!

    This message was sent with Python's smtplib.

如前所述,如果我从 If 语句中删除代码,它可以通过正确的主题行和正确的正文完成。也许我错过了一些明显的东西?

任何帮助将不胜感激。谢谢我的朋友们。

4

1 回答 1

3
    message = """\
    From: %s
    To: %s
    Subject: %s

    %s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

此消息在关键字From、、To等之前有空格Subject。因此这些关键字不能被识别为标题字段名称。所以这一切都成为消息体的一部分。

要解决此问题,请删除文本:

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

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

或者,为了保持缩进的可读性,

import textwrap
if X == 1:
    message = textwrap.dedent("""\
        From: %s
        To: %s
        Subject: %s
    
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT))
于 2013-05-30T06:49:57.957 回答