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 | |
---|---|
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
CodePudding user response:
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