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

Time:08-18

My code sends email in HTML format when executed.

The received email is basically very simple like:

Name: somename

sender = '[email protected]'
receiver = '[email protected]'

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

CodePudding user response:

You'd do it in a loop.

names = [
    ('Tom', '[email protected]'),
    ('Jack', '[email protected]'),
    ('Peter', '[email protected]')
]

for name, receiver in names:
    msg['Subject'] = "Email subject"
    msg['To'} = receiver
    html = ...

CodePudding user response:

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>
  • Related