Sending multiple Emails with Python based on csv problem

I am testing with python to send emails but I can’t send multiple emails from a csv file.

The CSV file looks like this

name email
name1 example@gmail.com
name2 another#gmail.com

Here is my code:

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
login = "joo123456h@gmail.com"
password = input("Type your password and press enter:")

message = """Subject: Order confirmation
To: {recipient}
From: {sender}

Hi {name}, thanks for your order! We are processing it now and will contact you soon"""
sender = "new@example.com"


context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.connect()     
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted    
    server.login(login, password)
with open("contacts.csv") as file:
        reader = csv.reader(file)
        next(reader)  # it skips the header row
        for name, email in reader:
                server.sendmail(
                sender,
                email,
                message.format(name=name, recipient=email, sender=sender)
            )
        print(f'Sent to {name}')

Error i get:

SMTPServerDisconnected: please run connect() first

Answer

I think problem with this block of code.

Code:

    server.connect()     
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted    
    server.login(login, password)

Complete code should be like as following:

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
login = "joo123456h@gmail.com"
password = input("Type your password and press enter:")

message = """Subject: Order confirmation
To: {recipient}
From: {sender}

Hi {name}, thanks for your order! We are processing it now and will contact you soon"""
sender = "new@example.com"


context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.connect('smtp.gmail.com', '587')
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted   
    server.login(login, password)
    
    with open("contacts.csv") as file:
            reader = csv.reader(file)
            next(reader)  # it skips the header row
            for name, email in reader:
                    server.sendmail(
                    sender,
                    email,
                    message.format(name=name, recipient=email, sender=sender)
                )
            print(f'Sent to {name}')

Let me know if it’s not working