3

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: %s\r\nTo: %s\r\nSubject: %s\r\n\

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


server = smtplib.SMTP(x)
server.sendmail(FROM, TO, message)
server.quit()

2 Answers 2

6

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>
Sign up to request clarification or add additional context in comments.

3 Comments

I can play around with it to get the formatting of the table to be in html now, but I cant get the from to and subject to work. Are you sure it should be server.sendmail(from_email, to_email, my_email.as_string()) ?
@Imccann, I did make some edits after I posted the answer. Did you see those?
ah yes got it to work now. Why do I need to add Content-Type: text/html; charset="us-ascii" to your message string:
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.