Python 2.7:如何将循环输出存入变量并用于邮件发送?
Got it, let's break this down for you. You're working with variable-length repeated JSON blocks, using a loop to process them—but right now you're just printing the output. You want to capture all that into a variable so you can use it flexibly for emails, right? Here's exactly how to do that:
1. 核心思路:用容器收集循环内容
Instead of printing each line directly, build up a string (or list of strings) as you loop through your JSON blocks. This gives you a single, reusable variable you can plug straight into your email body later.
示例1:字符串拼接(适合简单内容场景)
假设你已经有了处理JSON块的逻辑,只需调整输出方式:
import json # 模拟你的不定长重复JSON块 json_blocks = [ {"ticket_id": 101, "status": "resolved", "user": "Alice"}, {"ticket_id": 102, "status": "pending", "user": "Bob"}, # 更多动态生成的块... ] # 初始化空字符串存储最终内容 email_content = "" for block in json_blocks: # 提取并格式化你需要的信息 line = f"- Ticket #{block['ticket_id']}: {block['user']}'s request is {block['status']}\n" # 把每一行追加到变量中 email_content += line # 现在email_content就是所有循环输出的整合内容,直接用于邮件即可 print(email_content)
示例2:列表收集后合并(高效处理大量内容)
字符串拼接在循环中如果数据量较大,效率会偏低。用列表先收集每一行,最后合并成字符串更优:
email_lines = [] for block in json_blocks: line = f"- Ticket #{block['ticket_id']}: {block['user']}'s request is {block['status']}\n" email_lines.append(line) # 把列表中的所有行合并为一个完整字符串 email_content = "".join(email_lines)
2. 复杂JSON块的适配技巧
如果你的JSON块有嵌套结构,只需在循环里调整信息提取逻辑就行,比如:
for block in json_blocks: user_name = block["customer"]["name"] order_date = block["order"]["created_at"] product = block["order"]["items"][0]["name"] line = f"- {user_name} ordered {product} on {order_date}\n" email_lines.append(line)
3. 邮件格式优化(HTML版)
如果你的邮件需要更美观的HTML格式,可以直接把内容格式化为HTML标签:
email_lines = ["<ul>"] for block in json_blocks: line = f"<li>Ticket #{block['ticket_id']}: {block['user']}'s request is <strong>{block['status']}</strong></li>" email_lines.append(line) email_lines.append("</ul>") # 生成HTML格式的邮件内容 html_email_content = "\n".join(email_lines)
这样html_email_content就能直接作为邮件的HTML正文使用。
内容的提问来源于stack exchange,提问作者UsualSuspect7

