10

I'm trying to send an html email using python, MIMEMultipart, and smtp. The html is quite long, so I put all of the html in an html file. Now I want to import the html file into my python file (in the same folder) and set all of the html as a string in a python variable called html_string.

html:

<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Welcome to infinity2o</title>
      <style type="text/css">
        body {
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          padding-top: 0 !important;
          padding-bottom: 0 !important;
          margin: 0 !important;
          width: 100% !important;
          -webkit-text-size-adjust: 100% !important;
          -ms-text-size-adjust: 100% !important;
          -webkit-font-smoothing: antialiased !important;
        }
    .
    .
    .
    </head>
</html>

How do I import all of the html into my python file and set it equal to a variable:

python:

html_string = """
   <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
          <title>Welcome to infinity2o</title>
          <style type="text/css">
            body {
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              padding-top: 0 !important;
              padding-bottom: 0 !important;
              margin: 0 !important;
              width: 100% !important;
              -webkit-text-size-adjust: 100% !important;
              -ms-text-size-adjust: 100% !important;
              -webkit-font-smoothing: antialiased !important;
            }
        .
        .
        .
        </head>
    </html> """
1

3 Answers 3

33

You can open the file, read all its contents, and set it equal to a variable:

with open('html_file.html', 'r') as f:
    html_string = f.read()
Sign up to request clarification or add additional context in comments.

1 Comment

Like in @Tiago example, include encoding='utf-8' too: open(filename, 'r', encoding='utf-8'). Can avoid unnecessary errors :D
3

Just open the file as in any I/O.

with open('test.html', 'r') as f: 
        html_string = f.read()

Comments

3

You can simply use the following

fname = "FILE.html"
html_file = open(fname, 'r', encoding='utf-8')
source_code = html_file.read() 
print(source_code)

and it'll print the entire .html file as you can see in the following screenshot taken in Spyder

enter image description here

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.