Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

smtplib - Printing mutiple HTML tables using tabulate in python

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')]
    )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...