Question

I have a weird problem with a very simple python email script. The script by itself works fine, however when I use the script inside my existing code (inside an if statement) it seems to put the FROM,TO,SUBJECT AND TEXT fields inside the body of the email (not just the TEXT field)

The script

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

When I wrap it around an If statement, it goes haywire and puts everything into the email body.

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

This will give me an email like below

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.

As mentioned, If I remove the code from the If statement, it comes through fine, complete with the correct subject line and the correct body. Perhaps I am missing something obvious?

Any help would be appreciate. Thank you my friends.

Était-ce utile?

La solution

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

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

This message has spaces before the keywords From, To, Subject, etc. So these keywords are not recognized as header field names. So it all becomes part of the message body.

To fix this, dedent the text:

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

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

Or, to preserve the readability of the indentation,

import textwrap
if X == 1:
    message = textwrap.dedent("""\
        From: %s
        To: %s
        Subject: %s
    
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top