0

我有一段代码在 python 中运行 MySql 查询。然后,我将查询作为通过电子邮件发送的 HTML 文件返回。

一切都在运行,但发送的电子邮件<TABLE>在正文中给出。

我使用了本教程,但看不出有什么问题。请帮忙。

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 查询,只是没有显示在电子邮件正文中。

我缺少什么论据?

4

1 回答 1

0

我想出了这个问题的答案。我使用了这个例子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()
于 2014-10-14T19:51:49.043 回答