我在python编程中相当陌生。当我尝试使用python 2.7发送电子邮件时,出现错误:
from email.mime.text import MIMEText
import smtplib
msg = MIMEText("Hello There!")
msg['Subject'] = 'A Test Message'
msg['From']='[email protected]'
msg['To'] = '[email protected]'
s = smtplib.SMTP('localhost')
s.sendmail('[email protected]',['[email protected]'],msg.as_string())
print("Message Sent!")
File "C:\Python27\ArcGISx6410.3\lib\socket.py", line 571, in create_connection
raise err
error: [Errno 10061]
>>>
import smtplib
from smtplib import SMTP
try:
sender = '[email protected]'
receivers = ['xxx.com']
message = """ this message sending from python
for testing purpose
"""
smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login('xxx','xxx')
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
print "Error: unable to send email"
如果您运行了此代码,您将看到类似这样的错误消息,表明google不允许您通过代码登录
gmail更改的内容:
1。登录gmail
2。转到此链接https://www.google.com/settings/security/lesssecureapps
3。单击启用,然后重试代码
希望有帮助:)
但是如果您启用它,则会存在安全威胁
您的smtp服务器设置为localhost,您确定正确吗?错误是“连接打开”。您可能必须找到所用SMTP服务器的用户名/密码/地址/端口组合。
您使用的代码段并非旨在在Windows上运行,而是旨在在Linux上运行,在Linux上(通常)有一个服务监听本地主机的端口25。
对于Windows,您必须先连接到实际的邮件服务器,然后才能发送邮件。
请检查https://www.geeksmonk.com/articles/sending-mail-using-python/以找到使用python发送邮件的代码