-2

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()
stepad
  • 1
  • Have you looked for examples on how to send email with attachments using Python? There are similar questions here on stackoverlfow, such as https://stackoverflow.com/questions/3362600/how-to-send-email-attachments or https://stackoverflow.com/questions/11921188/how-to-send-email-with-pdf-attachment-in-python or https://stackoverflow.com/questions/9541837/attach-a-txt-file-in-python-smtplib, etc. – larsks Sep 05 '21 at 19:09
  • Yes, but those generally hard code the recipients, whereas I would like to automatically send several emails to a csv-list of recipients. – stepad Sep 06 '21 at 20:04

1 Answers1

0

This will only work using gmail and make sure you have manually set up special permissions on your gmail account for the program to be able to send email on behalf of you. The process is described here.

You can use other email address services for that you need to change the smtp server address and the smtp port number in line 32 accordingly and take care of any other additional steps required.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
body = """
Hi {name},\n\n This email was entirely generated in Python. So cool!
""".format(name="Name")

# details
sender = 'example1@gmail.com'  # my email
password = '&*password.$'  # my email's password
receiver = 'example2@gmail.com'  # receiver's email

msg = MIMEMultipart()
msg['To'] = receiver
msg['From'] = sender
msg['Subject'] = 'Testing Python Automation'
msg.attach(MIMEText(body, 'plain'))


pdfname = "mypdf.pdf"  # pdf file name
binary_pdf = open(pdfname, 'rb')
payload = MIMEBase('application', 'octate-stream', Name=pdfname)
payload.set_payload((binary_pdf).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=pdfname)
msg.attach(payload)

session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, password)
text = msg.as_string()
session.sendmail(sender, receiver, text)
session.quit()
print('[#] Mail Sent!')
Anaam
  • 124
  • 6