Search code examples
pythonhtmlsmtpmime

How to import html file into python variable?


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> """

Solution

  • 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()