Reputation: 149
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()
Upvotes: 3
Views: 12794
Reputation: 83
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)
Upvotes: 1
Reputation: 2470
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>
Upvotes: 6