python - 在 Python 中以 HTML 形式发送 MySQL 查询

标签 python html mysql python-2.7 pymysql

我有一段代码,我正在 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/

相关文章:

python - 在 Selenium Python 绑定(bind)中设置页面加载超时

python - 如何将具有重复索引条目的数据帧与具有唯一索引条目的数据帧合并?

mysql - 通过 Percona 工具包运行 Flyway 迁移

mysql - SQL向MySQL结果集添加汇总行

mysql按总和和最好成绩排名

python - Pandas 根据另一列的字典值添加列

python - 正则表达式从python中的字符串中提取子字符串

html - Itemscope 和 itemprop 处于同一级别

javascript - 页面可见性 API 是否先于脚本中的任何其他内容运行

html - 错误位置的 Chrome 验证消息气泡