Aweava
Aweava

Reputation: 105

Python code runs fine, until put into a function

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

Upvotes: 0

Views: 44

Answers (1)

Kevin
Kevin

Reputation: 76234

    ''' 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

Upvotes: 1

Related Questions