无法在python中登录gmail smtp服务器

时间:2015-05-11 11:07:53

标签: python error-handling smtp gmail server

我按照教程通过python发送电子邮件,但它返回SMTPAuthentication错误。以下是我的源代码:

import smtplib, getpass

# Connect to smtp server
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
print("Successfully connected to gmail.")

# User login
print("Please Login")
gmail_user = str(raw_input("Enter your email: "))
gmail_pwd = getpass.getpass("Enter your password: ")
smtpserver.login(gmail_user, gmail_pwd)

# Destination email
to = str(raw_input("Enter the email you would like to send to: \n"))

# Message contents
header = "To:" + to + "\n" + "From: " + gmail_user + "\n" + "Subject:testing \n"
print header
msg = header + '\n this is test message\n\n'

# Begin sending email
smtpserver.sendmail(gmail_user, to, msg)
print "Success!"

# Close smtpserver
smtpserver.close()

谁能告诉我什么错了?我很确定我输入了正确的电子邮件和密码。谢谢!

1 个答案:

答案 0 :(得分:0)

我猜这是错误:

SMTPAuthenticationError: Application-specific password required

您还可以尝试yagmail的标准设置:

import yagmail
yag = yagmail.Connect(gmail_user, gmail_pwd)
yag.send(to, 'testing', 'this is test message')

yagmail的目标是让您轻松发送垃圾邮件而不会有任何麻烦。它还提供了文档中常见错误的列表。

它还建议将用户帐户保存在密钥环中,这样您就不必再次编写用户名/密码了(特别是不要在脚本中写入);只运行一次yagmail.register(gmail_user, gmail_pwd)

希望有所帮助,随时查看documentation

相关问题