Reputation: 95
I have the following piece of code. The length of my_header_list and my_msg_list can change so I am looking to replace the following code with a for loop within the html.
def send_email(my_header_list, my_msg_list, recipients):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = ";".join([i for i in recipients])
mail.Subject = 'Summary | ' + str(datetime.now().strftime("%m-%d-%Y %H:%M"))
mail.Body = html = """\
<html>
<head></head>
<body>
<a href="https://www.awebsite.com">ABC</a>
<br>
<b>"""+str(my_header_list[0])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[0]).split("\n"))+ """
<br>
<b>""" +str(my_header_list[1])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[1]).split("\n"))+ """
<br>
<b>""" +str(my_header_list[2])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[2]).split("\n"))+ """
<br>
<b>""" +str(my_header_list[3])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[3]).split("\n"))+ """
<br>
<b>""" +str(my_header_list[4])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[4]).split("\n"))+ """
<br>
</p>
</body>
</html>
"""
mail.HTMLBody = (mail.Body)
mail.Send()
Upvotes: 1
Views: 1562
Reputation: 410
You can simply changed this string as follows
html = """\
<html>
<head></head>
<body>
<a href="https://www.awebsite.com">ABC</a>"""
for index in range(0,4):
html = html + """<br>
<b>"""+str(my_header_list[index])+ """</b>
<br>
""" +"<br/>".join(str(my_msg_list[index]).split("\n"))+ """
<br>
</p>
</body>
</html>
"""
Upvotes: 1
Reputation: 8372
Collect your lines in a list, join at the end.
def send_email(my_header_list, my_msg_list, recipients):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = ";".join([i for i in recipients])
mail.Subject = 'Summary | ' + str(datetime.now().strftime("%m-%d-%Y %H:%M"))
myhtml = []
myhtml.append("<html>")
myhtml.append("<head></head>")
myhtml.append("<body>")
myhtml.append('<a href="https://www.awebsite.com">ABC</a>')
for line in range(5):
myhtml.append("<br>")
myhtml.append("<b>"""+str(my_header_list[line])+ """</b><br>")
myhtml.append(""" +"<br/>".join(str(my_msg_list[line]).split("\n"))+ """)
myhtml.append("</p>")
myhtml.append("</body>")
myhtml.append("</html>")
mail.Body = "\n".join(myhtml)
mail.HTMLBody = (mail.Body)
mail.Send()
Upvotes: 2