我编写了一个 python 脚本来查询数据库并以 HTML 表格式显示数据。我怎样才能让这个代码以表格的形式显示在电子邮件中?
我尝试将代码粘贴到第二个脚本(EMAIL)的 html 标签内,但它不读取 python 代码,仅读取 HTML。
import pyodbc
import cgi
def htmlTop():
print("""Content-type:text/html\n\n
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8"/>
<title>My Tabmle</title>
</head>
<body>""")
def selectCOAStatus(cnxn, cursor):
cursor.execute('''SELECT * from mytable''')
data = cursor.fetchall()
return data
def htmlTail():
print("""</body>
</html>""")
def connectDB():
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=test;'
r'DATABASE=test;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()
return cnxn, cursor
def displayData(data):
print("<table border='1'")
print("<tr>")
print("<th>Date</th>")
print("<th>Count</th>")
print("<th>Status</th>")
print("</tr>")
for row in data:
print("<tr>")
print("<td>{0}</td>".format(row[0]))
print("<td>{0}</td>".format(row[1]))
print("<td>{0}</td>".format(row[2]))
print("</tr>")
print("</table>")
if __name__ == "__main__":
try:
htmlTop()
cnxn, cursor = connectDB()
data = selectCOAStatus(cnxn, cursor)
cursor.close()
displayData(data)
htmlTail()
except:
cgi.print_exception()
电子邮件代码
导入smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "[email protected] /cdn-cgi/l/email-protection"
you = "[email protected] /cdn-cgi/l/email-protection"
# Create message container - the correct MIME type is
multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML
version).
text = "Hi!\nHow are you?\nHere is the link you
wanted:\nhttp://www.python.org"
html = htmlTop()
# Record the MIME types of both parts - text/plain and
text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message,
in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('email.fpl.com')
# sendmail function takes 3 arguments: sender's address,
recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
我希望此 HTML 表格显示在我的电子邮件正文中。