如何将HTML文件导入python变量?

Hun*_*Liu 1 html python mime smtp

我正在尝试使用python,MIMEMultipart和smtp发送html电子邮件。html很长,因此我将所有html都放在html文件中。现在,我想将html文件导入到我的python文件中(在同一文件夹中),并将所有html设置为名为html_string的python变量中的字符串。

的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>
Run Code Online (Sandbox Code Playgroud)

如何将所有html导入我的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> """
Run Code Online (Sandbox Code Playgroud)

小智 8

您可以打开文件,读取其所有内容,并将其设置为变量:

with open('html_file.html', 'r') as f:
    html_string = f.read()
Run Code Online (Sandbox Code Playgroud)