Python SMTPResponseException:(535,b'5.7.8 不接受用户名和密码)

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

所以我试图在streamlit中创建一个联系我们页面。因此,我需要一个应用程序密码来访问我的 Gmail,以便我可以接收用户的邮件。起初我直接使用谷歌的密码。效果很好。当时我的代码是这样的

import smtplib, ssl

def send_email(message):
    host = 'smtp.gmail.com'
    port = 465

    username = 'My Mail'
    password = '**** **** ****'
    receiver = "My Other Mail"
    context = ssl.create_default_context()

    with smtplib.SMTP_SSL(host, port, context=context) as server:
        server.login(username, password)
        server.sendmail(username, receiver, message)

但后来当我希望我的密码更安全时。我把密码放在系统环境变量中。并稍微编辑了我的代码。编辑后我的代码看起来像这样

import smtplib, ssl
import os

def send_email(message):
    host = 'smtp.gmail.com'
    port = 465

    username = 'My Mail'
    password = os.getenv('Password')
    receiver = "My other mail"
    context = ssl.create_default_context()

    with smtplib.SMTP_SSL(host, port, context=context) as server:
        server.login(username, password)
        server.sendmail(username, receiver, message)

但是在我这样做之后,我总是收到一个错误,错误是:

SMTPResponseException: (535, b'5.7.8 Username and Password not accepted. For more information, go to\n5.7.8 https://support.google.com/mail/?p=BadCredentials d2e1a72fcca58-715e575cd80sm4330543b3a.203 - gsmtp')
Traceback:
File "C:\Users\safwa\AppData\Roaming\Python\Python312\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 85, in exec_func_with_error_handling
    result = func()
             ^^^^^^
File "C:\Users\safwa\AppData\Roaming\Python\Python312\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 576, in code_to_exec
    exec(code, module.__dict__)
File "G:\Projects and Courses\Python_\App2\pages\Contact_Us.py", line 17, in <module>
    send_email(message)
File "G:\Projects and Courses\Python_\App2\Send_email.py", line 13, in send_email
    with smtplib.SMTP_SSL(host, port, context=context) as server:
File "C:\Program Files\Python312\Lib\smtplib.py", line 284, in __exit__
    raise SMTPResponseException(code, message)

我厌倦了回到之前的代码并且它有效。但我希望将我的代码推送到我的 github 中。我不能只在那里分享我的应用程序密码。

我希望找到一种方法来保护我的密码并在 github 中上传我的项目。

python email ssl smtp
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.