Learn » Intro-Projects » Mail Merge.md

Mail Merge Project

For this project we will be starting with some example files. Download the .zip file to your Desktop and unzip it there:  https://s3.amazonaws.com/watpy/learn/mailmerge.zip

By the time we are done you will be able to take a spreadsheet of data including emails and send a custom email for every row form a gmail address.

For testing we will be using watpython@gmail.com so we don't spam each other. The password to the email account will be provided during the session

We will be taking everything you have already learned and a few new ideas to make this project work.

Goals

1. Practice developing Python

  • Open IDLE (Go back to the goals for your operating system if you need a refresher)  and click File > Open and find mailmerge.py. under your Desktop\mailmerge.
  • Open your command line and navigate to your Desktop and the folder we just downloaded (C:\Users\yourusername\Desktop\mailmerge). There type

    python mailmerge.py

This should produce this output:

Hello, World!
  • Change the string value in to print statement at the very bottom of the mailmerge.py in IDLE and save it (File > Save) or Control-S.
  • Use up in the command line to get the last command, it should be python mailmerge.py. Run the command and make sure you see the changed string.

Success!

2. Talk though the existing code

  • Document strings
  • Imports
  • Functions
  • if __name__ == "__main__"

3. Accept arguments

  • print(sys.argv)
  • Pass in arguments on the command line

4. Validate arguments

if len(sys.argv) < 4:
    print(usage)
    sys.exit(0)
  • Handle too many arguments
  • Capture arguments and validate

    subjectfilename = sys.argv[1] messagefilename = #?? csvfilename = #??

    if not os.path.isfile(subjectfilename): print("{0} is not a file.".format(subjectfilename)) sys.exit(0)

    Validate the rest are files

5. Read files

  • If you have Excel open data.xls and export as csv, if not just use data.csv.

    with open(subjectfilename, "r") as subjectfile: subject = subjectfile.read() print(subject)

Break!

6. Get email

from_email = raw_input("Your Gmail address: ")

7. Read the CSV and loop over rows

with open(csv_file_name, "r") as csv_file:
    rows = csv.DictReader(csv_file)

count = 0
for row in rows:
    print(row)
    count = count + 1

8. Print out emails to send

print_email(from_email,
    row['email'],
    subject.format(**row),
    message.format(**row))

9. Send flag

send = False
if len(sys.argv) == 5 and sys.argv[4] == "--send":
    send = True
    password = getpass()
    server = create_server(from_email, password)

10. Send emails!

if send:
    send_email(server,
               from_email,
               row['email'],
               subject.format(**row),
               message.format(**row))
else:
    print_email(from_email...