0

I have a piece of code where I am running a MySql query in python. I then return the query as an HTML file which is emailed.

Everything runs but the email that is sent gives <TABLE> in the body.

I used this tutorial and I do not see what's wrong. Please help.

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

When I go to the email message I can see the original text and the HTML query is there, just not showing up in the body of the email.

What argument am I missing?

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
DataTx
  • 1,839
  • 3
  • 26
  • 49

1 Answers1

0

I figured the answer to this problem. I used this example Sending HTML email using Python, and implemented into my problem

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()
Community
  • 1
  • 1
DataTx
  • 1,839
  • 3
  • 26
  • 49