Skip to content

Instantly share code, notes, and snippets.

@jaymzcd
Created August 22, 2011 12:48
Show Gist options
  • Select an option

  • Save jaymzcd/1162297 to your computer and use it in GitHub Desktop.

Select an option

Save jaymzcd/1162297 to your computer and use it in GitHub Desktop.
Logs into an smtp server using the data in the config and reads and sends HTML email
[global]
server: smtp.gmail.com
port: 587
user: jaymzcd@gmail.com
password: ???????
[message]
text: /tmp/email/plain.txt
html: /tmp/email/index.html
from: jaymzcd@gmail.com
addresses: /tmp/email/users.csv
subject: Hi It's an Email From Me
replacement: ##NAME##
#!/usr/bin/python2
import smtplib
import ConfigParser
import csv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmails():
cfg = ConfigParser.RawConfigParser()
cfg.read('mail.cfg')
txt_data = open(cfg.get('message', 'text')).read()
html_data = open(cfg.get('message', 'html')).read()
for row in csv.reader(open(cfg.get('message', 'addresses'))):
to_addy = row[0]
to_name = row[1]
txt_data = txt_data.replace(cfg.get('message', 'replacement'), to_name)
html_data = html_data.replace(cfg.get('message', 'replacement'), to_name)
txt_part = MIMEText(txt_data, 'plain')
html_part = MIMEText(html_data, 'html')
msg = MIMEMultipart('alternative')
msg['Subject'] = cfg.get('message', 'subject')
msg['From'] = cfg.get('message', 'from')
msg['To'] = to_addy
msg.attach(txt_part)
msg.attach(html_part)
server = smtplib.SMTP(cfg.get('global', 'server'), cfg.get('global', 'port')) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login(cfg.get('global', 'user'), cfg.get('global', 'password'))
server.sendmail(cfg.get('message', 'from'), to_addy, msg.as_string())
server.close()
if __name__=='__main__':
sendmails()
@jaymzcd
Copy link
Copy Markdown
Author

jaymzcd commented Aug 22, 2011

We needed to send about 100 slightly customized emails via a gmail account. Hence this script - it should work with any smtp server though that smtplib works with and just point it at your html & text versions (I used antiword to rip out the text from a doc into a file). Put all your addressees in a csv file with "email, name" rows and then run... Job done. Quick'n'dirty python controlled mailmerge/mass sending.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment