几天来,我一直在研究Stack Overflow如何通过Gmail发送电子邮件
smtplib
.如果我不想打开“不太安全的应用程序访问”,我终于明白了应该做什么的要点我已经切换到使用两步验证,并为python程序创建了一个应用程序密码。
这是我的代码:
import smtplib, ssl
from email.mime.text import MIMEText
def send_email_gmail(subject, message, destination):
# First assemble the message
msg = MIMEText(message, 'plain')
msg['Subject'] = subject
# Login and send the message
port = 465
my_mail = 'sample@gmail.com'
my_password = 'thepasswordtouse'
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server:
server.ehlo()
server.login(my_mail, my_password)
server.sendmail(my_mail, destination, msg.as_string())
send_email_gmail('Test subject', 'This is the message', 'sallysample@gmail.com')
然而,当我运行上面的代码时,我得到了一个
smtplib.SMTPAuthenticationError
:
Traceback (most recent call last):
File "/home/user/programs/python/testing/test.py", line 21, in <module>
send_email_gmail('Test subject', 'This is the message', 'sallysample@gmail.com')
File "/home/user/programs/python/testing/test.py", line 17, in send_email_gmail
server.login(my_mail, my_password)
File "/usr/lib/python3.8/smtplib.py", line 743, in login
raise last_exception
File "/usr/lib/python3.8/smtplib.py", line 732, in login
(code, resp) = self.auth(
File "/usr/lib/python3.8/smtplib.py", line 655, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials w10sm17413068qtk.90 - gsmtp')
我试过
server.ehlo()
在代码的各个地方,我尝试过使用SSL而不是SSL,我尝试过使用不同的代码结构,我尝试过创建和重新创建新的应用程序密码,我尝试过使用我的普通帐户和用户名登录,我尝试过使用我的用户名和电子邮件地址作为
server.login()
,我尝试在密码中使用空格,但没有空格,所有这些都会给出相同的错误消息。此外,这段代码运行在我通常登录的同一台设备上,因此它与未知设备无关。
有谁能解释一下为什么我不能登录我的Gmail帐户,以及如何做到这一点?