Sending personalized mass emails with different attachments
Here comes another challenge for this week. So, you are organizing an event, and some people will pay the costs via bank transfer. Therefore, you need to send email attachments (including banking details) to only those people who want to use that payment option. Let us also assume that you gave them IDs to recognize their payment. In the document that you will attach, you want to include those IDs as well, and that makes each document unique to each recipient. No problem.
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' email_data = csv.reader(open('email.csv', 'r')) email_pattern= re.compile("^.+@.+\..+$") for row in email_data: msg = MIMEMultipart() msg['From'] = 'your email' msg['Subject'] = subject fp = open('message.txt', 'r') body = MIMEText(fp.read()) fp.close() msg.attach(body) server = smtplib.SMTP('hostname', portnumber) server.starttls() server.login('your email', 'your password') if( email_pattern.search(row) ): del msg['To'] msg['To'] = row if(len(row) >= 5 and len(row) > 0): filename = row + '.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.sendmail('your email', [row], msg.as_string().format(row, row, row)) server.quit()
I created a for loop for each email. The reason being that you can overwrite the text for each email with varying information. However, you cannot overwrite attachment. You either need to delete the attachment or treat each email as a different object. I chose the latter. The names of attachments were in the row in the email.csv file. On line 30, you will see an if statement. If the number of rows is equal to 5 or bigger, and there is a row, it means that we have to add an attachment. For the people who did not want to use that payment option, we will leave this row empty.