-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()
2

1 Answer 1

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 = '[email protected]'  # my email
password = '&*password.$'  # my email's password
receiver = '[email protected]'  # 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!')
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the code example! However, this does not seem to send emails to all the recipients in a csv-file, right?
It should work to mail any address as long it's a valid one

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.