Python代码运行正常,直到放入函数

时间:2016-01-19 02:58:44

标签: python smtp messaging smtplib

所以我开发了python代码,它以文本消息的形式发送引用。它在一个简单的脚本中运行时运行正常。但是,一旦我将代码放入函数并调用函数,它就无法工作。它发送空白文本消息,而不是引用。

以下代码正在运行:

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

这是非功能性代码

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

1 个答案:

答案 0 :(得分:1)

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

也许sendmail对此字符串每行开头的空格敏感。尝试去缩小它们。

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