2016-01-19 16 views
0

因此,我開發了Python代碼,以文本消息的形式發送報價。它運行在一個簡單的腳本時運行正常。但是,一旦我將代碼放入一個函數並調用該函數,那麼它就無法工作。它發送一個空白的文本消息,而不是報價。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() 
+0

它看起來像你發送電子郵件,而不是短信。 – Chris

+1

如果您嘗試在函數中打印(引用),是否打印預期的文本? – elsherbini

+0

@elsherbini是的,它在兩種情況下打印相同的東西。 – Aweava

回答

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 
+2

好的建議。如果可行,OP可能希望使用['textwrap.dedent'](https://docs.python.org/3/library/textwrap.html#textwrap.dedent),這樣代碼可以很好地格式化,一切都會仍然工作。 – Chris

+0

不錯,謝謝!我認爲它必須採用文本格式,但我不認爲這是縮進。接得好! – Aweava

+0

@Aweava,如果這解決了你的問題,請記住[接受它](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。之後,當您贏得更多聲望時,您也可以向上或向下投票。 – Chris

相關問題