【发布时间】:2016-11-21 18:51:21
【问题描述】:
我正在做一个制作我自己的即时消息程序的项目,即使没有图形或任何东西,只是为了了解 python 中的内置模块。 在这里,我尝试编写一个代码,用户将输入用户想要的用户名和密码,然后将发送一封电子邮件(给用户),其中将包含一个 12 个字符的随机字符串,用户将将其输入回程序。不知何故,当我运行代码时,我的整个计算机都冻结了! 代码如下:
import smtplib
SMTPServer = smtplib.SMTP("smtp.gmail.com",587)
SMTPServer.starttls()
SMTPServer.login(USERNAME, PASSWORD)*
userEmail = raw_input("Please enter your e-mail: ")
if verifyEmail(userEmail) == False:
while True:
userEmail = raw_input("Error! Please enter your e-mail: ")
if verifyEmail(userEmail) == True:
break
randomString = generateRandomString()
message = """From: From Person <%s>
To: To Person <%s>
Subject: Ido's IM Program Registration
Your registration code is: %s
""" %(SERVEREMAIL, userEmail, randomString)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(SERVEREMAIL, userEmail, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
inputString = raw_input("Input generated code sent: ")
【问题讨论】:
-
您麻烦地设置了与 Gmail 的 SMTP 连接,然后不要使用它来发送您的电子邮件。相反,您使用
localhost创建一个新的 SMTP 连接并使用它。您实际上是在运行此脚本的计算机上运行邮件服务器吗? -
我一定误解了 SMTP 的工作方式,你的意思是我应该删除
smtpObj = smtplib.SMTP('localhost')并将下一行更改为SMTPServer.sendmail(SERVEREMAIL, userEmail, message),因为我在写@987654325 时已经创建了服务器@ ? -
除非您实际上是在与脚本相同的计算机上运行 SMTP 服务器,否则这听起来不错。
标签: python email crash smtp smtplib