繁体   English   中英

如何使用python发送电子邮件?

[英]How to send an email in python?

我想用Python发送电子邮件。 下面是一个示例代码:

#!/usr/bin/python

import smtplib

sender = 'test@gmail.com'
receivers = ['test@gmail.com']

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print("Send OK.")
except SMTPException:
   print("Send NOT OK.")

当我尝试运行该程序时,出现一些错误:

Traceback (most recent call last):
  File ".\sendEmail.py", line 16, in <module>
    smtpObj = smtplib.SMTP('localhost')
  File "C:\Python34\lib\smtplib.py", line 242,
    (code, msg) = self.connect(host, port)
  File "C:\Python34\lib\smtplib.py", line 321,
    self.sock = self._get_socket(host, port, se
  File "C:\Python34\lib\smtplib.py", line 292,
    self.source_address)
  File "C:\Python34\lib\socket.py", line 509, i
    raise err
  File "C:\Python34\lib\socket.py", line 500, i
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Nie mo

During handling of the above exception, another

Traceback (most recent call last):
  File ".\sendEmail.py", line 19, in <module>
    except SMTPException:
NameError: name 'SMTPException' is not defined

如何改进此代码以发送电子邮件? 谢谢。

看这行:

smtpObj = smtplib.SMTP('localhost')

您正在尝试连接到本地主机-您自己的计算机。 您是否正在运行SMTP服务器? 我不这么认为。

配置正确的SMTP服务器。 您可以使用您的个人电子邮件帐户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM