Skip to content

Instantly share code, notes, and snippets.

@tacke758
Created December 30, 2011 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tacke758/1538968 to your computer and use it in GitHub Desktop.
Save tacke758/1538968 to your computer and use it in GitHub Desktop.
Simple Mail Sender
sample@gmail.com Mr.Sample
foo@gmail.com Ms.Foo
# -*- coding: utf-8 -*-
# Author: tacke758 (tacke.jp@gmail.com)
# Reference: http://labs.unoh.net/2007/06/python_2.html
import smtplib
import csv
import sys
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
from getpass import getpass
if __name__ == '__main__':
#********** Settings **********
# utf8-encoded tab-delimited csv
# the first column is address and others are inserted strings
csvfile = 'address.dat'
encoding = 'ISO-2022-JP'
from_addr = 'hoge@gmail.com'
fromtxt_u = u'Registration'
subject_u = u'subject here'
smtp_user = from_addr
smtp_server = 'smtp.gmail.com'
smtp_port = 587
# error occurrs when num of '%s' != num of csv's column - 1
content_u = u'''Dear %s
Thank you for your registration to our service.
Regards,
Foobar Web Service
'''
#******************************
reader = csv.reader(file(csvfile, 'r'), delimiter='\t')
password = getpass()
s = smtplib.SMTP(smtp_server, smtp_port)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtp_user, password)
for row in reader:
to_addr = row[0]
insert_strs = map((lambda s: unicode(s, 'utf-8', 'ignore')), row[1:])
msg = MIMEText(content_u % tuple(insert_strs), 'plain', encoding)
msg['Subject'] = Header(subject_u, encoding)
msg['From'] = Header(fromtxt_u, encoding)
msg['To'] = to_addr
msg['Date'] = formatdate()
s.sendmail(from_addr, [to_addr], msg.as_string())
print 'sent to ' + to_addr
s.close()
print 'finished!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment