pythonsmtpsmtplib

Connection unexpectedly exception on sending mail using SMTP


I'm trying to send an email using SMTP and encountered a 'Connection unexpectedly closed' exception. I've checked all the parameters, including the SMTP server address and port. I'm using the password generated from my Google Account settings, and I've ensured that 'Signing in with 2-Step Verification' is turned on. Despite these checks, I'm still facing the issue. I would appreciate any help or insights on resolving this.

`from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
import ssl
import smtplib




# Email configuration
sender_email = my_email
app_password = my_password #generated from my Google Account settings

receiver_email = some_email


subject = 'Test Email'
body = 'This is a test email sent using smtplib in Python.'


# Create message
em = EmailMessage()
em['From'] = sender_email
em['To'] = receiver_email
em['Subject'] = subject
em.set_content(body)


# Gmail SMTP server configuration
smtp_server = 'smtp.gmail.com'
smtp_port = 465 


max_retries = 3
retry_delay_seconds = 5

for attempt in range(1, max_retries + 1):
    try:
        # Connect to the SMTP server
        with smtplib.SMTP(smtp_server, smtp_port) as smtp:
    # Log in
            smtp.login(sender_email, app_password)

    # Send mail
            smtp.sendmail(sender_email, receiver_email, em.as_string())

        print("Email sent successfully!")
        break  # Exit the loop if successful

    except smtplib.SMTPServerDisconnected as e:
        print(f"Attempt {attempt}: SMTPServerDisconnected - {e}")
        if attempt < max_retries:
            print(f"Retrying in {retry_delay_seconds} seconds...")
            time.sleep(retry_delay_seconds)
        else:
            print("Maximum retries reached. Exiting.")
            raise

    except Exception as e:
        print(f"Unexpected error: {e}")
        raise`

Solution

  • Let's address this step by step.

    1 Correct Use of SMTP Class and Port:

    2 Code Revision for SMTP_SSL:

    Here's how you should modify the code:

    import smtplib
    from email.message import EmailMessage
    
    # Email configuration
    sender_email = 'my_email'
    app_password = 'my_password'  # App password generated from Google Account settings
    receiver_email = 'some_email'
    
    # Create the email message
    em = EmailMessage()
    em['From'] = sender_email
    em['To'] = receiver_email
    em['Subject'] = 'Test Email'
    em.set_content('This is a test email sent using smtplib in Python.')
    
    # Gmail SMTP server configuration for SSL
    smtp_server = 'smtp.gmail.com'
    smtp_port = 465  # Port for SSL
    
    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as smtp:
            smtp.login(sender_email, app_password)
            smtp.send_message(em)
        print("Email sent successfully!")
    except Exception as e:
        print(f"An error occurred: {e}")