Rendering HTML in Python when sending e-mails using import smtplib

Question:

I am trying to send an e-mail using import smtplib. And I want it to render the html and send it in an e-mail. Unfortunately it currently just sends the html code in the e-mail. Any suggestion would be much appreciated.

My Code is below:

import smtplib
import pandas as pd

DEFAULT_EMAIL_SERVER = "x"
TO = ["[email protected]"]
FROM = "[email protected]"
SUBJECT = "TEST"
table = pd.read_excel('abc.xlsm')

body = '<html><body>' + table.to_html() + '</body></html>'
        TEXT = body


message = """From: %srnTo: %srnSubject: %srn

            %s
            """ % (FROM, ", ".join(TO), SUBJECT, TEXT)


server = smtplib.SMTP(x)
server.sendmail(FROM, TO, message)
server.quit()
Asked By: lmccann

||

Answers:

You can use the MIMEText object from email.mime.text to create an email that specifies it’s content as HTML.

from email.mime.text import MIMEText

message = '<html><body> <b>hello world</b> </body></html>'

my_email = MIMEText(message, "html")
my_email["From"] = "[email protected]"
my_email["To"] = "[email protected]"
my_email["Subject"] = "Hello!"

server = smtplib.SMTP(my_server)
server.sendmail(from_email, to_email, my_email.as_string())

This handles the formatting of the email header for you. .as_string() produces:

Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: [email protected]
To: [email protected]
Subject: Hello!

<html><body> <b>hello world</b> </body></html>
Answered By: alxwrd

To send html emails using smtplib I use the following code:

from email.message import EmailMessage

content = "<p>This is a paragraph!</p>"

msg = EmailMessage()
msg.set_content(content, subtype='html')
msg['Subject'] = "Subject"
msg['From'] = "SENDER"
msg['To'] = "RECEIVER"
with smtplib.SMTP("SERVER", 587) as smtp:
   smtp.starttls()
   smtp.login("SENDER", "PASS")
   smtp.send_message(msg)
Answered By: Crinela
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.