问题
I want to produce two HTML tables using tabulate package, but I am only able to produce one table and send mail.
Is it possible to put more than one html table into a message sent with smtplib and email? Whenever I use attach() for more than one thing, it only adds the first.
text = """
Hello, Friend.
Here is your data:
{table}
Regards,
Me
"""
html = """
<html>
<body>
<p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body>
</html>
"""
with open('input.csv') as input_file:
reader = csv.reader(input_file)
data = list(reader)
text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))
message = MIMEMultipart(
"alternative", None, [MIMEText(text), MIMEText(html,'html')]
)
回答1:
Yes. First you have to change the number of fields you want to substitute as tables:
text = """ [...] {table1} {table2} [...] """
Then you have to pass the content to format as kwargs:
text = text.format(table1=tabulate(data, headers="firstrow", tablefmt="grid"),
table2=your_new_table_tabulation)
Same you can do for html
String formatting in Python is no sort of attachment, but rather a substitution of content into a pre-formatted field. You can substitute as many fields as you'd like, putting the names you'd like, and with the content you'd like. Then, when you send the email, you will send a normal HTML file with the tables rendered into as HTML/text
I encourage you to check out: https://docs.python.org/3/library/string.html#string.Formatter.format
That is for Python's version 3.7. You have almost every Python's version available online.
来源:https://stackoverflow.com/questions/51930239/printing-mutiple-html-tables-using-tabulate-in-python