【发布时间】:2019-02-10 07:02:18
【问题描述】:
我可以使用 MYSQL 数据库从 python 发送电子邮件。在 MYSQL db 中可以找到发件人地址、收件人地址等。
它不允许我在数据库中有超过一排。我想要完成的是能够向每一行上的每个人发送邮件,这些人都有自己的 pdf 路径等。
如何遍历表格并逐行发送电子邮件?
Code Below:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password", database="maindb" )
mycursor = mydb.cursor()
mycursor.execute("SELECT Email FROM Email")
emailaddr = str(mycursor.fetchone()[0])
mycursor.execute("SELECT Subject FROM Email")
subject = str(mycursor.fetchone()[0])
mycursor.execute("SELECT Message FROM Email")
message = str(mycursor.fetchone()[0])
mycursor.execute("SELECT LinkToPdf FROM Email")
linktopdf = str(mycursor.fetchone()[0])
mycursor.execute("SELECT AttachName FROM Email")
attachname = str(mycursor.fetchone()[0])
mycursor.execute("SELECT FromAddr FROM Email")
fromaddr = str(mycursor.fetchone()[0])
mycursor.execute("SELECT UserName FROM Email")
username = str(mycursor.fetchone()[0])
mycursor.execute("SELECT PassWord FROM Email")
password = str(mycursor.fetchone()[0])
mycursor.execute("SELECT Port FROM Email")
port = str(mycursor.fetchone()[0])
mycursor.execute("SELECT HostName FROM Email")
hostname = str(mycursor.fetchone()[0])
print(hostname)
toaddr = "%s"% emailaddr
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = "%s"%emailaddr
msg['Subject'] = "%s"%subject
body = "%s"%message
msg.attach(MIMEText(body, 'plain'))
filename = "%s"%attachname
attachment = open("%s"%linktopdf + "%s"%attachname , "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('%s'%hostname, port)
server.starttls()
server.login("%s"%username, "%s"%password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
【问题讨论】: