Reputation: 2352
I have a code for sending an email if a criteria is matched:
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()
However, if I run the entire code, the email that is sent has empty subject and empty body and everything is placed in the "from" of the email.
If I run statement by statement (starting after the conditional) I get the email correctly. What am I missing here?
Upvotes: 2
Views: 56
Reputation: 1822
This is probably related to the way you are assigning the text block to the email_text variable. The text is indented, while the email should have the header fields at the beginning of the line. Try changing it to:
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" %(sent_from, ', '.join(sent_to), sent_subject, sent_body)
Upvotes: 3