2014-10-13 4 views
0

Python으로 MySql 쿼리를 실행하는 코드가 있습니다. 그런 다음 쿼리를 이메일로 보낸 HTML 파일로 반환합니다.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 protected]', 'pw') 

mail.sendmail('[email protected]', '[email protected]', htmlcode) 

mail.close() 

내가 원래 텍스트와 HTML 쿼리를 볼 수있는 전자 메일 메시지로 이동

은 이메일의 본문에 표시되지,있다.

어떤 논의가 빠졌습니까?

답변

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 = "[email protected]" 
you = "[email protected]" 

# 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()