有没有办法通过for循环向数据库中的所有电子邮件地址发送电子邮件?我不太确定for循环并需要帮助。
我关注此page电子邮件示例。 SQL语句为select email from table name
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com"]
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()
答案 0 :(得分:1)
您必须下载并导入正确的数据库界面。 (MySQL或SQL Server等)
然后做这样的事情:
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()
如果您不理解,请告诉我。