I thought that I was done sending mass emails. Ups, not really. This time, it was necessary to add attachments. No problem, I said to my colleague:) Yes, you can enjoy the moments of being problem solver:)
First, I saved the attachment to the same directory with my .py file, .csv file (for personalized messages), and .txt file (including the message text). Then, I needed to add three more modules (i.e., MIME Base, MIME Multipart, Encoders) from the email package.
I also used a function which I did not use in the first blog, “encode_base64“. Click on it to have further information about its use.
In order to add my message (i.e., subpart), and my document (i.e., another sub-part) to the emails I sent, I used “message.attach” method (Line 20 & Line 30, respectively). Line 23 is where it opens and reads the attachment. Line 25 is basically for uploading the attachment. Then, the attachment was encoded in base64 (Line 27).
import csv import re import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders subject = 'subject' msg = MIMEMultipart() msg['From'] = 'your email' msg['Subject'] = subject #(Your Email header) fp = open('message.txt', 'r') body = MIMEText(fp.read()) fp.close() msg.attach(body) filename = 'Your attachment.docx' attachment = open(filename, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= "+filename) msg.attach(part) server = smtplib.SMTP('your hostname', portnumber) server.starttls() server.login('your email', 'your password') email_data = csv.reader(open('email.csv', 'r')) email_pattern= re.compile("^.+@.+\..+$") for row in email_data: if( email_pattern.search(row[1]) ): del msg['To'] msg['To'] = row[1] server.sendmail('your email', [row[1]], msg.as_string().format(row[0], row[2], row[3])) server.quit()
You might see that on the 42nd line, there are more rows (row[2], row[3] ) than in my previous blog post. That is because I needed to modify more than one type of information. (Previously, we only altered recipient’s names). To be able to change more than one type of information, I needed to change the email text accordingly.
The example of the email text in its current/new form:
Dear {0}, It is nice to hear from you. Your birthday which is on {1} will be celebrated at {2}
Let us assume that {0} represents the name of the recipient, and it should change with each new recipient. {1} represents each recipient’s unique birthday, and {2} represents the unique location of the birthday party for each person. With each email I sent, three types of information (name, birthday, party location) will be updated. Makes sense?
Cheers!
Note: If you want to read my first blog about sending mass emails, and have further information, click here.