Home > Mobile >  Python: HTML table should be striped
Python: HTML table should be striped

Time:04-09

As you can see below in the code, the dataframe dfges is sent by mail to. Currently, the table looks very old fashioned and therefore I would like to have a fancier table. Would it be possible to have the table the same size and shape but with one row in white and the other in light gray? Thus, the table should be striped to the end, where just one row is white and the other gray.

dfges = pd.concat(nachrichten, axis='index')

from email.message import EmailMessage
from_mail = [email protected]

from_password = '.....'

to_mail = ['[email protected]']
smtp_server = "smtp.gmail.com"
smtp_port = 465

def send_email(smtp_server, smtp_port, from_mail, from_password, to_mail):
    '''
        Send results via mail
    '''

    msg = EmailMessage()
    msg['Subject'] = 'Subject'
    msg['From'] = from_mail
    msg['To'] = ', '.join(to_mail)

    html = """\
    <html>
    <head></head>
    <body>
    {0}
    </body>
    </html>
    """.format(dfges.to_html(index=False, escape=False))
    msg.set_content(html, 'html')

    with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
        server.ehlo()
        server.login(from_mail, from_password)
        server.send_message(msg)
        server.quit()
send_email(smtp_server, smtp_port, from_mail, from_password, to_mail)
´´´

CodePudding user response:

Turns out you can use the CSS property output

Full code:

import pandas as pd
import smtplib

dfges = pd.concat([pd.DataFrame()], axis='index')

from email.message import EmailMessage
from_mail = '[email protected]'

from_password = '.....'

to_mail = ['[email protected]']
smtp_server = "smtp.gmail.com"
smtp_port = 465

def send_email(smtp_server, smtp_port, from_mail, from_password, to_mail):
  '''
  Send results via mail
  '''

  msg = EmailMessage()
  msg['Subject'] = 'Subject'
  msg['From'] = from_mail
  msg['To'] = ', '.join(to_mail)

  html = f"""
  <!DOCTYPE html>
  <head>
  <style>
  tr:nth-child(even) {{
    background-color: #f2f2f2;
  }}
  </style>
  </head>
  <body>
  {dfges.to_html(index=False, escape=False)}
  </body>
  </html>"""
  msg.set_content(html, 'html')

  with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
      server.ehlo()
      server.login(from_mail, from_password)
      server.send_message(msg)
      server.quit()
send_email(smtp_server, smtp_port, from_mail, from_password, to_mail)
  • Related