import smtplib
import MySQLdb
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com","another@user.com","many@users.com"]
#SQL data access part
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='emaildatabase')
cursor = db.cursor()
cursor.execute('select email from tablename where email is not null')
db.commit()
rows = cursor.fetchall()
for item in rows:
TO.append(item)
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()