如何将Python生成的DataFrame样式化HTML表格插入邮件HTML正文
The issue you're facing is that you're inserting the variable name output as a literal string in your email HTML, instead of injecting the actual HTML content stored in the variable. Here's how to fix it:
Step 1: Use Python String Formatting to Inject the Table HTML
Since output contains the full styled table HTML (including the <table> tags), you can directly insert it into your email body using f-strings (the most readable method for Python 3.6+) or string concatenation.
Example with F-Strings (Recommended)
Rewrite your email body as an f-string, replacing the literal output with {output} where you want the table to appear:
email_html = f""" <html><body> <p>Dear Team </p> <p>sjhfkajsfbjkasbkjas</p> <p>please review and confirm your views on the below </p> 1. Is account still valid? <br> 2. Does account still required for the user? <br> 3. Are roles currently permission to the users’ account still valid as per his/her current role?<br> <p> Please find the table below which indicates the reasons </p> {output} <!-- This inserts the full table HTML here --> <p>Appreciate your feedback by <b><u>18th March 2021.</u></b></p> Regards,<br> ABC<br> </body></html> """
Example with String Concatenation (Older Python Versions)
If you're using Python pre-3.6, concatenate the email sections with the output variable:
email_html = """ <html><body> <p>Dear Team </p> <p>sjhfkajsfbjkasbkjas</p> <p>please review and confirm your views on the below </p> 1. Is account still valid? <br> 2. Does account still required for the user? <br> 3. Are roles currently permission to the users’ account still valid as per his/her current role?<br> <p> Please find the table below which indicates the reasons </p> """ + output + """ <p>Appreciate your feedback by <b><u>18th March 2021.</u></b></p> Regards,<br> ABC<br> </body></html> """
Step 2: Verify the Result
When you generate email_html, it will now include the full styled table from output instead of the word "output". You can print it to check:
print(email_html)
Why This Works
- The f-string
{output}replaces the placeholder with the actual HTML content stored in theoutputvariable (which is the result ofs.hide(axis='index').to_html()). - Since
outputalready contains the complete<table>element with all your styling, you don't need to wrap it in additional<table>tags—just insert it directly where you want the table to appear in the email.
Additional Notes
- Ensure that your email client supports HTML rendering (most modern clients do).
- If you encounter any styling issues, double-check that your DataFrame styling is correctly applied (your original styling code looks correct, but you can verify by printing
outputseparately).
内容的提问来源于stack exchange,提问作者The Great

