从 python 脚本发送电子邮件

Sending emails from a python script

我正在编写一个 python 测试,使用 unittest 和 selenium webdriver 来测试我们的服务器是否已关闭,如果没有,我会发送电子邮件通知我。我目前正在努力实现电子邮件功能。这是我当前的代码。当 运行 时,程序似乎 运行,但永远不会结束,也不会发送电子邮件。 (即在命令行中,程序看起来好像是 运行ning,因为它没有给出任何错误,您必须先退出“运行ning”程序,然后才能输入另一个命令)。 我当前的代码是:

 #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@gmail.com", "password")
            msg = "Testing if server is down" 
            server.sendmail("email@gmail.com", "email@gmail.com", 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:\Users3255\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.

您需要开始与邮件服务器的对话并启用加密:

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

由于smtplib.SMTP()调用不成功,可以尝试SMTP_SSL465端口:

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("email@gmail.com", "password")
msg = "Testing if server is down" 
server.sendmail("email@gmail.com", "email@gmail.com", msg)