2017-08-08 169 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

这给了我一个回溯错误。我将完整的错误添加为帖子的编辑以保留格式。 –