0

So I developed python code that sends a quote in the form of a text message. It runs properly when ran in a simple script. However, once I put the code into a function and call the function then it fails to work. It sends a blank text message, instead of the quote.

Here's the code working:

import smtplib
import urllib2

''' open webpage and grab randomly generated quote '''
response = urllib2.urlopen("http://inspirationalshit.com/quotes")
page = response.read()
split = page.split('<blockquote>')[1]
split = split.split('class="text-uppercase";>')[1]
quote = split.split('</p>')[0].strip()

'''email credentials (throwaway account) '''
username = "**********@gmail.com"
password = "*********"
phone = "********@vtext.com"
message = quote

''' format the email '''
msg = """From: %s
To: %s
Subject:
%s""" % (username, phone, message)

''' send the email '''
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(username, password)
server.sendmail(username, phone, msg)
server.quit()

Here's the nonfunctional code

import urllib2
import smtplib
import schedule
import time


def job():
    print "RAN"
    ''' open webpage and grab randomly generated quote '''
    response = urllib2.urlopen("http://inspirationalshit.com/quotes")
    page = response.read()
    split = page.split('<blockquote>')[1]
    split = split.split('class="text-uppercase";>')[1]
    quote = split.split('</p>')[0].strip()

    '''email credentials (throwaway account) '''
    username = "*********@gmail.com"
    password = "********"
    phone = "********@vtext.com"
    message = quote

    ''' format the email '''
    msg = """From: %s
    To: %s
    Subject:
    %s""" % (username, phone, message)
    print msg
    ''' send the email '''
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(username, password)
    server.sendmail(username, phone, msg)
    server.quit()


job()
Aweava
  • 75
  • 1
  • 5

1 Answers1

1
    ''' format the email '''
    msg = """From: %s
    To: %s
    Subject:
    %s""" % (username, phone, message)
    print msg

Maybe sendmail is sensitive to the whitespace at the beginning of each line of this string. Try de-indenting them.

    ''' format the email '''
    msg = """From: %s
To: %s
Subject:
%s""" % (username, phone, message)
    print msg
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 2
    Good suggestion. If that works, the OP may want to use [`textwrap.dedent`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent) so the code can be formatted nicely and everything will still work. – ChrisGPT was on strike Jan 19 '16 at 03:08
  • Nice that did it, thanks! I assumed it had to do something with the text format, but I didn't think it was the indent. Good catch! – Aweava Jan 19 '16 at 03:11