Search code examples
pythonhtmlsmtplib

How to loop over list or dict and display in HTML format with f-string


My code sends email in HTML format when executed.

The received email is basically very simple like:

Name: somename

sender = 'abc@gmail.com'
receiver = 'xyz@gmail.com'

msg['Subject'] = "Email Subject"
msg['From'] = sender
msg['To'] = receiver

html = f'''\
       <table>
         <tr>
            <td>Name: {name}</td>
         </tr>
       </table>
       '''

send_msg = MIMEText(html, 'html')
msg.attach(send_msg)
s = smtplib.SMTP(;localhost')
s.sendmail(sender, receiver, msg.as_string())
s.quit()

This works if i have a value of variable, lets say name=Tom. But now I have a list of Names like ['Tom', 'Jack', 'Peter]. How can I loop over this list and pass it to HTML?

Excpected output would be:

Name: Tom

Name: Jack

Name: Peter


Solution

  • Here is how you can compose multiple tr's in a loop:

    names = ['Tom', 'Jack', 'Peter']
    trs = []
    for name in names:
        trs.append(f'''\
      <tr>
        <td>Name: {name}</td>
      </tr>''')
    table_content = '\n'.join(trs)
    html = f'''\
    <table>
    {table_content}
    <table>
    '''
    print(html)
    

    Prints:

    <table>
      <tr>
        <td>Name: Tom</td>
      </tr>
      <tr>
        <td>Name: Jack</td>
      </tr>
      <tr>
        <td>Name: Peter</td>
      </tr>
    <table>