Приложение Python FastAPI не может войти на SMTP-сервер Gmail. Получение неверных учетных данныхPython

Программы на Python
Ответить
Anonymous
 Приложение Python FastAPI не может войти на SMTP-сервер Gmail. Получение неверных учетных данных

Сообщение Anonymous »

У меня есть пароль приложения, созданный Google Mail (16 символов), при попытке отправить электронное письмо через smtp.gmail.com. Вот код Python, который я использую:

Код: Выделить всё

def send_html_email(to_email: str, subject: str):
"""
Send an HTML email using smtplib
"""
logging.debug(f"Preparing to send email to {to_email} with subject '{subject}'")  # Log email details
# SMTP server configuration (you can set these as environment variables)
smtp_username = "Tokeri51"  # Use sender_email from config
smtp_password = sender_password

if not smtp_username or not smtp_password:
raise ValueError("Sender email and password must be set in the configuration")

con = ssl.create_default_context()
logging.debug(f"SSL context created for secure connection {con}")  # Log SSL context creation
# Create message
msg = MIMEMultipart('alternative')
msg\['Subject'\] = subject
msg\['From'\] = sender_email or smtp_username
msg\['To'\] = to_email

# Attach HTML content
# Create the email content using Jinja2 template
data = {
'username': "admin",
'reset_link': "https://example.com/reset-password?token=abc123",
'expiration_minutes': 30
}

# Set up Jinja2 environment to load templates from the templates directory
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('email_template.html')
# Render the template with the dynamic data
html_content = template.render(data)
logging.debug(f"Rendered HTML content")  # Log the rendered HTML content for debugging
html_part = MIMEText(html_content, 'html')
msg.attach(html_part)

try:
# Create SMTP connection
logging.debug(f"Connecting to SMTP server {smtp_server}:{smtp_port}")  # Log SMTP connection details
server = smtplib.SMTP(smtp_server, smtp_port)
logging.debug(f"Connected to SMTP server")  # Log successful connection
server.starttls(context=con)
logging.debug(f"After TLS encryption")
logging.debug(f"Logging in to SMTP server as {sender_email} with {sender_password\[:4\]}\*\*\*\*")  # Log login attempt
server.login(sender_email, smtp_password)
logging.debug(f"Logged in to SMTP server as {sender_email}")  # Log successful login
# Send email
server.sendmail(sender_email, to_email, msg.as_string())
logging.debug(f"Email sent to {to_email}")  # Log successful email sending
server.quit()

return {"message": "Email sent successfully"}

except Exception as e:
logging.error(f"Failed to send email: {str(e)}")  # Log the error details
raise HTTPException(status_code=500, detail=f"Failed to send email: {str(e)}")
Вызов server.login завершается с ошибкой из-за неверных учетных данных.

Код: Выделить всё

535, b'5.7.8 Username and Password not accepted.'
  • Python версии 3.13.7
  • Версия кода Visual Studio: 1.112.0 (настройка пользователя)
  • Зафиксировать: 07ff9d6178ede9a1bd12ad3399074d726ebe6e43
  • Дата: 2026-03-17T18:09:23Z

    E />
  • ElectronBuildId: 13470701
  • Хром: 142.0.7444.265
  • Node.li>

    V8: 14.2.231.22-electron.0
  • ОС: Windows_NT x64 10.0.19045
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»