Skip to main content
 首页 » 编程设计

python之从 python 脚本发送电子邮件

2025年02月15日26tintown

我正在使用 unittest 和 selenium webdriver 编写一个 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@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:\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. 

请您参考如下方法:

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

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() 调用不成功,您可以在端口 465 上尝试 SMTP_SSL:

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)