-1
for i in range(3):
    gmail_user = 'email'
    gmail_password = 'pass'
    
    sent_from = gmail_user
    to = ['email']
    subject = 'Lorem ipsum dolor sit amet'
    body = rand_quote
    
    email_text = ("""\
    From: %s
    To: %s
    Subject: %s
    
    %s
    """ % (sent_from, ", ".join(to), subject, body))
    
    try:
        smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        smtp_server.ehlo()
        smtp_server.login(gmail_user, gmail_password)
        smtp_server.sendmail(sent_from, to, email_text)
        smtp_server.close()
        print ("Email sent successfully!")
    except Exception as ex:
        print ("Something went wrong….",ex)

When I remove the for loop the code runs great with the subject and body sending properly however when I try to run something like the code above the email comes is sent as such.

  • first you could use `print()` to see what you have in variables. It is called `"print debuging"` and it can help to see problem in code. Maybe it adds some extra text (or empty line) before headers and it treats your `Subject: %s` as `body` instead of `header` – furas Feb 17 '22 at 12:46

1 Answers1

0

When you moved text """ """ then it added spaces before From:, To:, Subject: and it treads it as part of body.

You have to move all lines in """ """ to the left.

for i in range(3):
    gmail_user = 'email'
    gmail_password = 'pass'
    
    sent_from = gmail_user
    to = ['email']
    subject = 'Lorem ipsum dolor sit amet'
    body = rand_quote
    
    email_text = ("""\
From: %s
To: %s
Subject: %s
   
%s
""" % (sent_from, ", ".join(to), subject, body))

    try:
        smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        smtp_server.ehlo()
        smtp_server.login(gmail_user, gmail_password)
        smtp_server.sendmail(sent_from, to, email_text)
        smtp_server.close()
        print ("Email sent successfully!")
    except Exception as ex:
        print ("Something went wrong….",ex)

BTW:

See also @tripleee comment below.

Some examples in documentation: email.examples

furas
  • 134,197
  • 12
  • 106
  • 148
  • 1
    But more fundamentally, creating an SMTP message by pasting strings together is extremely error-prone; you should use the `email` library instead, which knows how to cover all the pesky corner cases. Note that old instructions which mention `MIMEText()` and related classes are outdated for modern Python; you should prefer the `EmailMessage` API introduced in Python 3.6 (and actually available already in 3.3, though then not yet as an official library). – tripleee Feb 17 '22 at 14:22
  • @tripleee yes, this is good point. I added this to answer. – furas Feb 17 '22 at 14:28