I am working on a project using Python whereby I send out emails in bulk to a list of contacts in a CSV file.
I can get the email sending working fine but I want to be able to add some error handling if there are some missing values in the CSV file.
My CSV file simply includes: record_id, retailer, first_name, last_name and email.
I want to be able to capture these 'errors' using 'if' statements and add them to an empty list.
I will then use the populated list to store the information of what the missing values are so that I can use that list to present the errors elsewhere in the code (still unsure as to where I will want to display the errors).
The issue I am having is that I am unable to add the values in my 'if' statements to the empty list. It only prints the empty list.
Here is the sample of my code where the email sending section is:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
try:
server.login(sender_email, password)
except SMTPAuthenticationError:
print("Username and/or password you entered is incorrect")
try:
with open("contacts.csv") as file: # Sending Multiple Personalized Emails using a CSV file
reader = csv.reader(file)
next(reader) # Skip header row
missing = []
for record_id, retailer, first_name, last_name, email in reader:
if not retailer:
missing.append("Testing")
continue
if not retailer:
missing.append("Record ID " + record_id + " has Retailer name missing!")
continue
if not first_name:
missing.append("Record ID " + record_id + " has First name missing!")
continue
if not last_name:
missing.append("Record ID " + record_id + " has Last name missing!")
continue
if not email:
missing.append("Record ID " + record_id + " has Email missing!")
continue
print(missing)
server.sendmail(
sender_email,
email,
message.as_string().format(
record_id=record_id,
retailer=retailer,
first_name=first_name,
last_name=last_name,
email=email,
previous_month=previous_month,
year=year),
)
print("Emails sent!")
except Exception as e:
print("Emails not sent!")
print(e)
except SMTPException as e2:
print(e2)
Aucun commentaire:
Enregistrer un commentaire