修复主单号邮件内容重复问题

Vibe Coding 使用 AI 回答

代码问题:

刚才给出的代码,做到不能一一对应,不同主单号的邮件内容全是一样的

代码解决方案:

要解决不同主单号邮件内容相同的问题,需要确保在循环处理每个主单号时,正确提取并替换模板中的动态变量。以下是修改后的代码:

import os
import pandas as pd
from string import Template
import win32com.client as win32
import tempfile

# 读取数据
df = pd.read_excel('data.xlsx')
main_order_nos = df['主单号'].unique()  # 获取唯一主单号

# 加载邮件模板
with open('mail_template.html', 'r', encoding='utf-8') as file:
    template_content = file.read()

email_contents = []  # 存储所有邮件内容

# 遍历每个主单号生成邮件
for main_order_no in main_order_nos:
    # 获取当前主单号的所有行
    rows = df[df['主单号'] == main_order_no]
    
    # 提取邮件中需要动态替换的字段(以第一行为基础提取固定信息)
    first_row = rows.iloc[0]
    mail_no = first_row['运单号']
    receiver_fullname = first_row['客户姓名']
    product = first_row['货物品名']
    quantity = first_row['件数']
    weight = first_row['重量']
    volume = first_row['体积']
    
    # 动态生成费用表格(处理多行费用)
    fee_table_rows = []
    for _, row in rows.iterrows():
        fee_table_rows.append(f"""
        <tr>
            <td>{row['费用项目']}</td>
            <td>{row['金额']}</td>
        </tr>
        """)
    fee_table = "\n".join(fee_table_rows)
    
    # 替换模板变量
    template = Template(template_content)
    email_content = template.safe_substitute(
        main_order_no=main_order_no,
        mail_no=mail_no,
        receiver_fullname=receiver_fullname,
        product=product,
        quantity=quantity,
        weight=weight,
        volume=volume,
        fee_table=fee_table  # 插入动态生成的表格
    )
    
    email_contents.append(email_content)  # 添加到结果列表

# 示例:发送邮件(实际使用时取消注释)
# for i, content in enumerate(email_contents):
#     outlook = win32.Dispatch('Outlook.Application')
#     mail = outlook.CreateItem(0)
#     mail.Subject = f"订单通知 - 主单号 {main_order_nos[i]}"
#     mail.HTMLBody = content
#     mail.Display(True)  # 或使用 mail.Send()

关键修改说明:

  1. 多行数据处理

    • 使用 rows = df[df['主单号'] == main_order_no] 获取当前主单号的所有行
    • 费用项目通过循环 rows.iterrows() 动态生成表格行
  2. 动态模板替换

    • 使用 safe_substitute 确保变量未匹配时保持原样
    • 主模板中需包含 $fee_table 占位符用于插入动态表格
  3. 邮件模板示例 (mail_template.html)

<html>
<body>
  <p>主单号: $main_order_no</p>
  <p>运单号: $mail_no</p>
  <p>客户姓名: $receiver_fullname</p>
  <p>货物品名: $product</p>
  <p>件数: $quantity | 重量: $weight | 体积: $volume</p>
  
  <h3>费用明细:</h3>
  <table border="1">
    <tr><th>费用项目</th><th>金额</th></tr>
    $fee_table
  </table>
</body>
</html>

注意事项:

  1. 确保Excel数据列名与代码中的字段名一致(如主单号运单号等)
  2. 如果存在多行数据,固定信息(如客户姓名)默认取第一行,如有特殊需求需调整逻辑
  3. 实际发送邮件时需取消注释邮件发送代码,并完善收件人等信息

此方案确保每个主单号生成唯一的邮件内容,并正确处理一个主单号对应多条费用记录的情况。