从python脚本发送电子邮件

时间:2017-08-08 15:44:10

标签: python email smtp python-unittest smtplib

我正在使用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.

1 个答案:

答案 0 :(得分:1)

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

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)