我可以使用MYSQL数据库从python发送电子邮件。在MYSQL数据库中,可以找到发件人地址,收件人地址等。
它不允许我在数据库中有多于一行。我要完成的工作是能够将邮件发送到每一行都有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()
答案 0 :(得分:0)
您一次可以选择多个字段。示例:选择AttachName,FromAddr,UserName,PassWord,FROM FROM Email。
您也可以通过检查结果进行循环。
# other code
result = mycursor.fetchone()
while result:
# your code to
# process the result
result = mycursor.fetchone()