0

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?

  • 1
    Sounds similar to https://stackoverflow.com/questions/54351740/how-can-i-use-f-string-with-a-variable-not-with-a-string-literal – Drdilyor May 30 '21 at 17:17
  • As an aside, you seem to be following some ancient guide for how to send email in Python. The `email` library from Python 3.6+ is a lot more straightforward to use; new code should probably avoid the clunky old API. – tripleee May 30 '21 at 18:43

1 Answers1

0

Instead of defining individual variables for name and age, better define a mapping between the placeholders and the target values:

value_map = {
    'age': 25,
    'name': "Bob"
}

Then, use the format() method of your template string. Note that you forgot to read() the file object. Something like:

html_template = open('example.html','r').read()
## Replace the placeholders
html_format = html_template.format(**value_map)
## Continue from there...

Another note: there's a typo in your example.html, a square bracket instead of a curly one.

Philo
  • 169
  • 2
  • 4