I'm trying to write a python script to send an email using smtplib and but imports an html file with f-strings (this is a local file that is secure and trusted). I can hard code the html in the function that sends the email, but I want to clean it up; the function file that contains all my definitions is getting too big to look at when troubleshooting.
This is what I've done so far...
The file that I'll be working with is example.html
. Here is it's contents:
<html>
<head>
</head>
<body>
Hello my name is {name}. I am {age] years old.
</body>
</html>
Here is the python code:
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
name = 'Bob'
age = '25'
sender_email = 'emailaddress@emailaddress.com'
sender_password = 'emailpassword'
receiver_email = 'receiveremail@emailaddress'
message = MIMEMultipart("alternative")
message["Subject"] = "This is a test email"
message["From"] = sender_email
message["To"] = receiver_email
html_format = open('example.html','r')
list_of_html_strings = [html_format]
total_html = "".join(list_of_html_strings)
part1 = MIMEText(html_format, "html")
message.attach(part1)
with smtplib.SMTP_SSL("smtp.gmail.com", 465, ) as server:
server.noop()
server.login(sender_email, sender_password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
html_format.close()
This works but it sends the html without being formatted. Any idea on what the code would look like to get it to work with being formatted?