[Python] Unable to send emails using the SMTP Python library

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm encountering an issue while trying to send OTP emails using SMTP (Simple Mail Transfer Protocol) in Python. Despite verifying the provided credentials (email and password), I keep getting an authentication error.

    Here is the error message from the logs:

    Failed to send email: (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
    d75a77b69052e-4746b3106b9sm84101401cf.18 - gsmtp') 127.0.0.1 - - [05/Mar/2025 07:34:22] "PUT /forget_password HTTP/1.1" 200 - Code

    Here is the code snippet I’m using to send emails:

    python

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from api.config import PASSWORD, MAIL

    def send_otp(email, otp):
    """
    Sends an OTP to the specified email address.

    Args:
    email (str): The recipient's email address.
    otp (str): The OTP to be sent.

    Sends the OTP via email using SMTP.
    """
    sender_email = MAIL
    sender_password = PASSWORD
    subject = "Your OTP Code"
    body = f"Your OTP code is {otp}. It is valid for 10 minutes."

    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = email
    message["Subject"] = subject
    message.attach(MIMEText(body, "plain"))

    try:
    server = smtplib.SMTP("smtp.gmail.com", 587)
    # server.starttls() # Uncommented this if using TLS
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, email, message.as_string())
    server.quit()
    except Exception as e:
    print(f"Failed to send email: {e}")`


    Troubleshooting Steps Taken Verified that the email and password are correct.

    Tested the SMTP server address (smtp.gmail.com) and port (587).

    Verified that SMTP authentication is enabled.

    Continue reading...

Compartilhe esta Página