[Python] Error while authenticating a Google account from a Python Script

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    Im doing an script in Python for an application. If there is any issue related with the main function, it should report it sending an email to an specific user.

    I use the next code:

    # Configure server and port
    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    from_email = EMAIL_SENDER
    to_email = EMAIL_RECEIVER
    #password ="xxxx xxxx xxxx xxxx"
    password = os.getenv('EMAIL_PASSWORD')

    if not password:
    print("Error: No se encontró la contraseña del correo en las variables de entorno.")
    return

    # Create message
    subject = f"Alerta"
    body = f"Alerta"

    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(from_email, password)
    text = msg.as_string()
    server.sendmail(from_email, to_email, text)
    server.quit()
    print(f"Correo enviado a {to_email}")
    except Exception as e:
    print(f"Error al enviar correo: {e}")


    The problem is that i get the next error:


    Error al enviar correo: (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 5b1f17b1804b1-4406d5bbd5fsm142651745e9.22 - gsmtp')
    ​

    I've tried to use the application password of Google but it doesn't still work.

    I've tried the same with an outlook account but kind of the same error. Is there any other way to validate user and password? Or bypass it?

    Continue reading...

Compartilhe esta Página