我有一段代码,我正在 python 中运行 MySql 查询。然后,我将查询作为 HTML 文件返回,并通过电子邮件发送。
一切正常,但发送的电子邮件给出 <TABLE>
体内。
我用过这个tutorial我不明白有什么问题。请帮忙。
import pymysql
import os
import HTML
conn = pymysql.connect(host='localhost', port=1000, user='users', passwd='pw', db='database')
cur = conn.cursor()
#mysql query
query = ("""select * from table""")
cur.execute(query)
rows = cur.fetchall()
for row in rows:
for col in row:
print "%s," % col
print "\n"
htmlcode = HTML.table(rows)
print htmlcode
import smtplib
content = 'email report'
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('email@email.com', 'pw')
mail.sendmail('email@email.com', 'email@email.com', htmlcode)
mail.close()
当我转到电子邮件时,我可以看到原始文本和 HTML 查询,只是没有显示在电子邮件正文中。
我缺少什么论据?
最佳答案
我找到了这个问题的答案。我用这个例子Sending HTML email using Python ,并实现到我的问题中
import pymysql
import os
import HTML
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
conn = pymysql.connect(host='localhost', port=1000, user='users', passwd='pw', db='database')
cur = conn.cursor()
#mysql query
query = ("""select * from table""")
cur.execute(query)
htmlcode = HTML.table(rows)
# me == my email address
# you == recipient's email address
me = "me@me.com"
you = "you@you.com"
# 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 = htmlcode
# 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.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()
关于python - 在 Python 中以 HTML 形式发送 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345816/