Python批量邮件项目中通过if语句向空列表添加CSV缺失值错误的问题
问题根因
print(missing)位置错误:你把打印语句放在了所有缺失值校验和continue之后,只有字段完整的记录才会执行打印,存在缺失的记录触发continue后直接跳过了这一步,自然看不到最新的错误信息。- CSV格式非法:你提供的测试CSV第5行末尾多了一个逗号,第4、5、6行末尾的括号注释也不符合CSV规范,会导致
csv.reader读取到的字段数和你代码里解包的5个变量不匹配,直接触发外层异常终止循环,后续的缺失记录根本没有走到校验逻辑。 - 异常捕获顺序颠倒:
SMTPException是Exception的子类,你把通用Exception捕获块写在前面,所有SMTP相关异常都会被优先捕获,后面的SMTPException分支永远不会生效。
修复后的完整代码
import ssl import smtplib import csv from smtplib import SMTPAuthenticationError, SMTPException context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: try: server.login(sender_email, password) except SMTPAuthenticationError: print("输入的用户名或密码错误") try: with open("contacts.csv", encoding="utf-8") as file: reader = csv.reader(file) next(reader) # 跳过表头 missing = [] for row in reader: # 先校验字段数量,避免解包报错 if len(row) != 5: missing.append(f"行数据异常:预期5个字段,实际获取{len(row)}个,行内容:{row}") continue record_id, retailer, first_name, last_name, email = row # 去除字段前后空格再校验,避免空格导致的假匹配 retailer = retailer.strip() first_name = first_name.strip() last_name = last_name.strip() email = email.strip() if not retailer: missing.append(f"Record ID {record_id} 缺失零售商名称!") continue if not first_name: missing.append(f"Record ID {record_id} 缺失名字!") continue if not last_name: missing.append(f"Record ID {record_id} 缺失姓氏!") continue if not email: missing.append(f"Record ID {record_id} 缺失邮箱地址!") continue server.sendmail( sender_email, email, message.as_string().format( record_id=record_id, retailer=retailer, first_name=first_name, last_name=last_name, email=email, previous_month=previous_month, year=year ), ) # 所有记录处理完统一打印缺失值列表 print("缺失值错误详情:", missing) print("邮件发送流程执行完毕!") except SMTPException as e2: print(f"SMTP异常:{e2}") except Exception as e: print(f"邮件发送失败:{e}")
额外注意事项
请先清理你的测试CSV文件,删除每行末尾的括号注释,以及第5行多余的逗号,修正后CSV内容如下:
record_id,retailer,first_name,last_name,email 1,Store 1,Bob,Doe,example@example.com 2,Store 2,Jane,Lang,example@example.com 3,Store 3,Bill,Rowe,example@example.com 4,Store 4,Rachel,Greene, 5,Store 5,,Geller,example@example.com 6,,Joey,Tribiani,example@example.com
内容的提问来源于stack exchange,提问作者Calogero Savarino
相关产品推荐
相关产品推荐

