dailylog 8-10-20
Bulk Emailing using Python
PROBLEM: There are a bunch of emails I want to send to congress.
SOLUTION: AUTOMATE THE BORING STUFF, WITH PYTHON!!
PROBLEM: The way in the book doesn’t immediately work because – get this – google wants to be EXTRA SECURE (HOW DARE THEY, jk jk jk) and requires an EXTRA app password.
SOLUTION: … get an app password.
PROBLEM: This is scary and I don’t know how to do this.
SOLUTION: FUCKING LEAN IN. GOOGLE IS HERE FOR YOU. (It’s actually quite easy. Google profile > security > app passwords > add app password > copy and paste that string into below)
Here is a tidy template script that I ended up using.
_subject = "I love the flowers"
_from_email = "kdosburn@gmail.com"
_from_name = "Kendra Ryan"
_bcc = "claracaraway42@gmail.com"
_message = "Thank you for the lovely bouquet! They made my day."
# CONNECT TO GMAIL
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login('kdosburn@gmail.com', 'MY_SUPER_SECRET_APP_PASSWORD')
# READ THE CSV OF RECIPIENTS
import pandas as pd
csv = pd.read_csv('ATBS_emails_test.csv')
from email.message import EmailMessage
from email.headerregistry import Address
def compose_email(NAME):
email = """
Dear {name},
{message}
Sincerely,
{signoff} """.format(name=NAME, message=_message, signoff=_from_name)
return email
# ITERATE THROUGH THE CSV
for index, row in csv.iterrows():
text = compose_email(row['NAMES'])
msg = EmailMessage()
msg.set_content(text)
msg['Subject'] = _subject
msg['From'] = Address(_from_name, _from_email)
msg['To'] = row['EMAILS']
msg['Bcc'] = _bcc
s.send_message(msg)
receipt = 'Sent to {name} at {email}'.format(name=row['NAMES'], email=row['EMAILS'])
print(receipt)