无法使用Python发送电子邮件

时间:2016-03-07 16:42:26

标签: python email smtp smtplib

我有这个代码,因为我正在尝试使用Python发送电子邮件。

def Mail():
   import smtplib
   import textwrap
   SERVER = "localhost"

   FROM = "fromemail"
   TO = ["toemail"] 

   SUBJECT =(input('What is the subject of your E-Mail'))

   TEXT =(input('What do you want the E-Mail to say?'))

   message = textwrap.dedent("""\
   From: %s
   To: %s
   Subject: %s

   %s
   """ % (FROM, ", ".join(TO), SUBJECT, TEXT))

   server = smtplib.SMTP(SERVER)
   server.sendmail(FROM, TO, message)
   server.quit()

这是我收到的错误消息。

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    Mail()
  File "E:\Coursework\EMail.py", line 26, in Mail
    server = smtplib.SMTP(SERVER)
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 241, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 322, in connect
    (code, msg) = self.getreply()
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 375, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

1 个答案:

答案 0 :(得分:0)

&#39;连接意外关闭&#39;显示服务器可能已启用但无法创建与smtplib的连接。

您可以检查端口25 smtp服务的状态以验证,

# netstat -an | grep -i :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN

然后,检查占用端口25的服务的状态,

# netstat -plnt | grep -i :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 30860/master

你可能会有同样的, 然后只检查主/后缀进程的状态,

# systemctl status postfix

如果您将错误突出显示为,

致命:无法使用&#34; inet_protocols = ipv4&#34;

处理套接字类型AF_INET6

然后快速转到 /etc/postfix/main.cf 的postfix配置文件,检查是否有此文本并取消注释,

inet_protocols = ipv4

然后重启postfix,

# systemctl restart postfix

然后检查状态,希望你不应该得到任何错误。 然后检查python是否能够连接到SMTP服务器!

$ python -c 'import smtplib; smtplib.SMTP("localhost");'

你不应该得到任何表明python能够连接到SMTP服务器的输出。

您现在可以运行电子邮件发送脚本了!