无法使用 Python 发送电子邮件 - gmail“5.7.8 用户名和密码不被接受”

时间:2021-02-04 16:16:27

标签: python email automation smtp gmail-api

我正在尝试使用 python 发送电子邮件,

  1. 我确定插入的用户名和密码。
  2. 在 Gmail 上启用了安全性较低的访问。
  3. 启用解锁验证码

仍然无法正常工作,这是我收到的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\smtplib.py", line 734, in login
    raise last_exception
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\smtplib.py", line 723, in login
    (code, resp) = self.auth(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\smtplib.py", line 646, 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 b4sm5524089wrn.12 - gsmtp')

这是我编码的方式:

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

#envirnment variables
username = '*****.gmail.com'
password = '********'

def send_mail(text='Email Body', 
              subject='Hello World',    
              from_email='Happy Dog<HappDogy.gmail.com>', 
              to_email=None, 
              html=None):
              assert isinstance(to_email, list)
              msg = MIMEMultipart('alternative')
              msg ['From'] = from_email
              msg ['To'] = ', '.join(to_email)
              msg ['Subject'] = subject
              
              txt_part = MIMEText(text, 'plain')
              msg.attach(txt_part)
              
              if html != None:
                html_part = MIMEText('<h1>This is working </h1>', 'html')
                msg.attach(html_part)
              
              msg_str = msg.as_string()

              #login to my smtp server
              server = smtplib.SMTP(host='smtp.gmail.com', port=587)
              server.ehlo()
              server.starttls()
              server.login(username, password)
              server.sendmail(from_email, to_email, msg_str)
              server.quit()

有什么帮助吗?

0 个答案:

没有答案