You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现输入ID匹配CSV行发邮件时出现群发问题如何解决?

问题根源

你遇到的群发问题是两个基础错误共同导致的:

  1. 对比值的类型和格式不匹配
    你通过input获取的retailer_id是整数类型(比如输入1得到的是int(1)),但CSV中Retailer列存储的是带前缀的字符串(比如"ID 1"),二者内容格式、类型完全不同,直接对比永远不会得到预期结果,校验规则完全失效。
  2. 使用了错误的比较运算符
    代码中用is not做值对比是完全错误的:Python里is/is not用来判断两个对象的内存地址是否一致,只有对比值相等的小整数、字符串常量时才会偶然符合预期,正常的值对比应该用!=/==。

修复方案

只需要统一对比两端的格式,再修正比较运算符即可,下面是可直接使用的修改后的CSV遍历逻辑:

try:
    with open("contacts.csv") as file:
        reader = csv.reader(file)
        next(reader)  # 跳过表头
        missing = []
        # 先生成预期的Retailer字符串格式,避免循环内重复计算
        target_retailer = f"ID {retailer_id}"
        for Retailer, Retailer_Name, Parent_Retailer, Email in reader:
            valid = True
            if not Retailer.strip():
                missing.append(f"Retailer {Retailer} 缺少Retailer ID!")
                valid = False
            if not Retailer_Name.strip():
                missing.append(f"Retailer {Retailer} 缺少Retailer名称!")
                valid = False
            if not Parent_Retailer.strip():
                missing.append(f"Retailer {Retailer} 缺少上级名称!")
                valid = False
            if not Email.strip():
                missing.append(f"Retailer {Retailer} 缺少邮箱地址!")
                valid = False
            # 修正后的ID匹配校验
            if Retailer.strip() != target_retailer:
                missing.append(f"Retailer {Retailer} ID不匹配!")
                valid = False
            if valid:
                server.sendmail(
                    sender_email,
                    Email,
                    message.as_string().format(
                        Retailer=Retailer,
                        Retailer_Name=Retailer_Name,
                        Parent_Retailer=Parent_Retailer,
                        Email=Email,
                        previous_month=previous_month,
                        year=year,
                        retailer_id=retailer_id
                    )
                )
        print(missing)
    print("邮件发送完成!")
except SMTPException as e2:
    print(e2)
except Exception as e:
    print("邮件未发送!")
    print(e)

额外注意事项

你贴出的原代码中with open块下存在多余的file行、缩进错误的问题,修复时要注意统一代码块缩进,否则会出现逻辑执行异常。

内容的提问来源于stack exchange,提问作者Calogero Savarino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:39:04