I am a beginner programmer and I am trying to write a program that automatically sends personalized emails to a list of receivers in a csv file with a pdf attachment.
My current code sends personalized emails but I don't know how to add an attachment. Also, I think it's best practice to write the program in a function but I don't know how to do that either.
It would be greatly appreciated if anyone could help me out. Also, I want to keep it as simple as possible so that I still understand what every line of code does.
import os
import smtplib, ssl
import csv 
# Sender credentials (from environment variables)
email_address = os.environ.get("email_user")
email_pass = os.environ.get("email_app_pass")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: 
    server.login(email_address, email_pass) # Log into sender email account
    # Email information
    subject = "Testing Python Automation"
    body = """ Hi {name},\n\n This email was entirely generated in Python. So cool!
    """
    msg = f"Subject: {subject}\n\n{body}"
    with open("contacts_test.csv") as file:
        reader = csv.reader(file)
        next(reader) # Skip header row
        for name, email in reader:
            server.sendmail(email_address, email, msg.format(name=name))
    file.close()
server.quit()