-4

I have a python script sending emails via a Gmail SMTP setup shown below which works fine. However when I try to turn this into a function it no longer sends any emails. Any help you can give me would be appreciated.

import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

sender = 'account@gmail.com'
password = 'password'
recipient = ['user@Email1.com', 'user@Email2.com']
subject = 'Gmail SMTP Test'
body = 'blah blah blah'

body = "" + body + ""

headers = ["From: " + sender,
       "Subject: " + subject,
       "To: " + ", " .join(recipient),
       "MIME-Version: 1.0",
       "Content-Type: text/html"]
headers = "\r\n".join(headers)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()

If I try to wrap this into a function it no longer sends an email. I have tried several diffrent varaiations on the def SendEmail() with no luck.

import smtplib

def SendEmail(self): 
    SMTP_SERVER = 'account.gmail.com'
    SMTP_PORT = 587

    sender = 'account@gmail.com'
    password = 'Password'
    recipient = ['user@Email1.com', 'user@Email2.com']
    subject = 'Gmail SMTP Test'
    body = 'blah blah blah'

    body = "" + body + ""

    headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + ", " .join(recipient),
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, password)

    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

1 Answers1

4

You forgot to call a function. Plus, you don't need self argument:

import smtplib

def SendEmail():
    SMTP_SERVER = 'account.gmail.com'
    SMTP_PORT = 587

    sender = 'account@gmail.com'
    password = 'Password'
    recipient = ['user@Email1.com', 'user@Email2.com']
    subject = 'Gmail SMTP Test'
    body = 'blah blah blah'

    body = "" + body + ""

    headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + ", " .join(recipient),
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, password)

    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

SendEmail()

Also, it might be a good idea to move your constants like SMTP_SERVER in a separate config file or just move outside of the function. Plus, it would look nicer if you'll pass recipient, subject, body variables as function arguments instead of hardcoding them inside the function.

Also, this session.ehlo (no parenthesis) line does nothing.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195