我的电子邮件和密码正确,但我无法使用我的脚本发送电子邮件。
import smtplib
content ="hello"
mail = smtplib.SMTP("smtp.gmail.com",587)
mail.ehlo()
mail.starttls()
mail.login('[email protected]','password')
mail.sendmail('[email protected]','[email protected]',content)
mail.close()
我遇到了和你一样的问题,但我找到了这篇文章,我可以解决它:smtp错误:535 5.7.8 Go中的gmail不接受用户名和密码
您必须在 myaccount.google.com/security 中启用 2FA
(如你所见,实际上我已经激活了它)
然后您需要来这里创建一个新应用程序:https://security.google.com/settings/security/apppasswords
现在,它会给您带来一个类似 XXXX XXXX XXXX 的代码,您必须使用该代码而不是您的实际密码
import smtplib
from email.mime.text import MIMEText
# Configuration
port = 465 #465 for SSL | 587 for TTL
smtp_server = "smtp.gmail.com"
sender_mail = "<[email protected]>"
password = "XXXX XXXX XXXX XXXX" #App code generated by google
receiver_email = ", ".join([<[email protected]>, ...])
# Plain text content
text = """\
Hello world
"""
# Create MIMEText object
message = MIMEText(text, "plain")
message["Subject"] = "Plain text email"
message["From"] = sender_email
message["To"] = receiver_email
# Send the email (VIA SSL) port = 465
with smtplib.SMTP_SSL(smtp_server, port) as server:
server.ehlo()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
# Send the email (VIA TTL) port = 587
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo()
server.starttls() # Secure the connection
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print('Sent')
希望它可以帮助您或其他人:)
您的凭据前后需要一个空格,如下所示:
mail.login(' [email protected] ',' password ')
mail.sendmail(' [email protected] ',' [email protected] ',content)
然后就可以了。
完整的代码示例,在我的程序中运行:
emailpassword = ' password '
emailsend = ' [email protected] '
emailreceive = ' [email protected] '
import smtplib
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
type(smtpObj)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(' [email protected] ', emailpassword)
smtpObj.sendmail(emailsend, emailreceive, 'Subject: test\nThis is an automated email.')
smtpObj.quit()