通过 gmail 发送电子邮件的 Python 脚本拒绝接受用户名和应用程序密码?

问题描述 投票:0回答:1

我正在尝试使用 python 学习一些电子邮件自动化。到目前为止,这是我的脚本:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Email configuration
sender_email = 'sendingemail@gmail'
sender_password = 'myapppassword'
receiver_email = '[email protected]'
subject = 'Subject of the Email'
message = 'This is the body of the email.'

# Create a MIMEText object to represent the email message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))

# Connect to the SMTP server (in this example, Gmail)
smtp_server = 'smtp.gmail.com'
smtp_port = 587

try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()  # Secure the connection
    server.login(sender_email, sender_password)
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)
    print('Email sent successfully')
except Exception as e:
    print('Email not sent. An error occurred:', str(e))
finally:
    server.quit()

我不断收到此错误:

电子邮件未发送。发生错误:(535,b'5.7.8 用户名和密码不被接受。了解更多信息 5.7.8 https://support.google.com/mail/?p=BadCredentials y63-20020a253242000000b00d7497467d36sm2031898yby.45 - gsmtp')

有什么想法为什么这不起作用吗?

想要设置一个自动化脚本来使用 python 发送电子邮件。我只是想收到提到的电子邮件。

python smtp gmail smtplib
1个回答
0
投票

这里的问题是,由于身份验证问题,Google 不接受登录。通常是在启用双因素身份验证时引起的。您可以登录

https://myaccount.google.com/apppasswords
来创建应用专用密码。或者更好的解决方案是使用 Mailgun (https://www.mailgun.com/) 等服务(如果您将其用于测试目的)。设置起来很容易。您每天可以通过它发送有限数量的电子邮件。但对于学习目的来说,这已经足够了。在那里您将获得用于发送电子邮件的 api 和 smtp 设置。您可以使用其中任何一个。

mailgun

© www.soinside.com 2019 - 2024. All rights reserved.