2017-08-08 223 views
2

我正在使用unittest和selenium webdriver編寫python測試來測試我們的服務器是否關閉,併發送電子郵件通知我如果不是。我目前正在致力於實現電子郵件功能。這是我現在的代碼。運行時,程序似乎運行,但永遠不會結束,並且永遠不會發送電子郵件。 (即在命令行中,程序看起來好像正在運行,因爲它不會給出任何錯誤,並且在輸入另一個命令之前必須先逃離「正在運行」的程序)。 我當前的代碼是:從python腳本發送電子郵件

#tests for if server is up and notifies if it is not 
    import unittest 
    from selenium import webdriver 
    from selenium.webdriver.common.keys import Keys 
    import os 
    import time 
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary 
    from selenium.webdriver.common.action_chains import ActionChains 
    from urllib.request import urlopen 
    from html.parser import HTMLParser 
    import smtplib 


    class PythonOrgSearch(unittest.TestCase): 

      server = smtplib.SMTP('smtp.gmail.com', 587) 
      server.login("[email protected]", "password") 
      msg = "Testing if server is down" 
      server.sendmail("[email protected]", "[email protected]", msg) 

    if __name__ == "__main__": 
     unittest.main() 

我不清楚爲什麼,這並不工作,並希望任何見解。謝謝!

編輯

當更改代碼的建議,我得到了以下錯誤:

Traceback (most recent call last): 
    File "testServerIsUp.py", line 14, in <module> 
    class PythonOrgSearch(unittest.TestCase): 
    File "testServerIsUp.py", line 18, in PythonOrgSearch 
    server.starttls() #and this method to begin encryption of messages 
    File "C:\Users\663255\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 751, in starttls 
    "STARTTLS extension not supported by server.") 
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. 

回答

1

你需要開始對話與郵件服務器並啓用加密:

server = smtplib.SMTP('smtp.gmail.com', 587) 
server.ehlo() 
server.starttls() #and this method to begin encryption of messages 
server.login("[email protected]", "password") 
msg = "Testing if server is down" 
server.sendmail("[email protected]", "[email protected]", msg) 

由於smtplib.SMTP()呼叫未成功,您可以在端口465上嘗試SMTP_SSL

server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
server.login("[email protected]", "password") 
msg = "Testing if server is down" 
server.sendmail("[email protected]", "[email protected]", msg) 
+0

它仍然不起作用,具有相同的問題。在我像這樣運行之後,我想也許它需要一個server.close()來修復它,但那也不起作用。有什麼建議? –

+1

請參閱我最近的編輯。 – Ajax1234

+0

這給了我一個回溯錯誤。我將完整的錯誤添加爲帖子的編輯以保留格式。 –