0

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 [email protected]
name2 another#gmail.com

Here is my code:

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
login = "[email protected]"
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 = "[email protected]"


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
0

1 Answer 1

1

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 = "[email protected]"
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 = "[email protected]"


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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.