如何优化Python生成HTML邮件正文的条件内容追加方式?
优化Python生成邮件正文逻辑:移除隐藏段落依赖
需求背景
我是HTML开发新手,目前用Python生成邮件正文,需求是勾选应用里的复选框时,在邮件内添加对应分类内容。原实现是预先设置多个display:none的隐藏段落,通过if条件替换对应内容,现在希望优化逻辑,无需依赖隐藏段落,直接在条件判断中追加内容。
优化后的代码
def update_body_mail_email(): # 基础邮件模板,移除所有隐藏段落 base_body = '''<html> <head> <meta charset="UTF-8"> <title>Your Email Title</title> </head> <body> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tr> <td width="510" style="width:382.75pt;background:#0076CE;padding:0cm 5.4pt 0cm 5.4pt; height:69.55pt"> <p class="MsoNormal"><a name="_MailAutoSig"><span style="font-size:15.0pt; font-family:"Arial",sans-serif;color:#F2F2F2;mso-no-proof:yes"> Notification</span><span style="mso-no-proof:yes"><o:p></o:p></span></a></p> </td> </tr> <tr> <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"> <p style="font-size: 16px; color: #666666;">Dear CC,</p> <p style="font-size: 16px; color: #666666;">RITMXXXXXXX and the following items need to be provided and to be attached in the RITMXXXXXXX</p> <!-- 动态内容插入占位符 --> {dynamic_content} <p style="font-size: 16px; color: #666666;">Best regards,<br></p> </td> </tr> </table> </body> </html> ''' dynamic_content = [] # 根据复选框状态追加对应内容 if checkbox_documents.get(): check_sub() dynamic_content.append(''' <p style="font-size: 16px; color: #666666"><strong>Documents to be attached to Request:</strong></p> <ul> <li style="font-size: 16px; color: #666666"><strong>Implementation Instructions:</strong> Explain in detail how the change is deployed, roles or groups involved, and tools used. </ul> ''') if checkbox_description.get(): dynamic_content.append(''' <p style="font-size: 16px; color: #666666"><strong>Description: </strong></p> <ul> <li style="font-size: 16px; color: #666666">What is Scope of this Standard change activity. Provide detail, clear and concise description in 2 or 3 sentences of what is being deployed.</li> ''') if checkbox_configuration_item.get(): dynamic_content.append(''' <p style="font-size: 16px; color: #666666"><strong>List of Config:</strong></p> ''') if checkbox_category.get(): dynamic_content.append(''' <p style="font-size: 16px; color: #666666"><strong>Standard Type [choose one of the below]:</strong></p> <ul> <li style="font-size: 16px; color: #666666">Application – Code</li> <li style="font-size: 16px; color: #666666">Application & Database – Code</li> </ul> ''') # 拼接动态内容并替换模板占位符 body_mail = base_body.format(dynamic_content=''.join(dynamic_content)) return body_mail
优化说明
- 移除冗余占位:基础模板彻底删除了所有隐藏段落,避免无效HTML代码残留
- 动态内容收集:用列表统一收集勾选复选框对应的HTML片段,替代多次字符串替换操作,逻辑更直观
- 模板化替换:通过占位符
{dynamic_content}统一插入动态内容,后续新增复选框只需追加新片段,无需修改基础模板 - 性能更优:字符串拼接效率高于多次
replace操作,代码可维护性更强
内容的提问来源于stack exchange,提问作者Rafael Muller
相关产品推荐
相关产品推荐

