Skyee
Skyee

Reputation: 25

Sending emails in python via loop

Is there a way to send emails to all the email addresses in the database via for loops? I'm not very sure on for loops and needs help.

I followed this page for email sample. SQL statement would be select email from table name

import smtplib

SERVER = "localhost"

FROM = "[email protected]"
TO = ["[email protected]"] 

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()

Upvotes: 0

Views: 3125

Answers (1)

Roan
Roan

Reputation: 932

You will have to download and import the correct Database interface. (MySQL or SQL Server etc.)
Then do something like this:

    import smtplib
    import MySQLdb

    SERVER = "localhost"

    FROM = "[email protected]"
    TO = ["[email protected]","[email protected]","[email protected]"] 

    #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()

Let me know if you don't understand.

Upvotes: 1

Related Questions