如何用Python自动化实现Outlook向多用户发送不同内容的邮件
Outlook邮件自动化循环仅执行一次的修复方案
核心问题排查
- Outlook发送方法大小写错误:win32com调用Outlook的邮件发送方法为大写的
Send(),你代码中使用小写mail.send()会触发COM接口异常,第一次执行后直接终止循环,这是最高发的诱因。 - Outlook实例重复初始化:你将
win32.Dispatch('outlook.application')写在循环内部,每次循环都新建Outlook实例,第一次发送后资源未释放会导致后续调用阻塞、报错,该初始化操作只需执行一次,应移到循环外。 - 无异常捕获机制:循环执行过程中如果出现无效邮箱、HTML格式错误、权限问题等报错,没有异常捕获会直接终止整个流程,也无法定位具体报错点。
- 数据源校验缺失:需先确认读取到的收件人列表长度是否符合预期,避免CSV读取异常、字段名不匹配导致实际只有1条收件人数据。
- HTML正文格式不规范:正文代码存在重复
<body>标签、未闭合标签,可能触发Outlook发送校验失败,进而终止循环。
修复后可运行代码
import win32com.client as win32 import pandas as pd # 读取数据 dtest = pd.read_csv('details.csv') dt1 = dtest de = pd.read_csv('email_name.csv') de_l = dt1['Email_id'] list_c = list(de_l) # 先确认收件人列表长度是否正确 print(f"总收件人数:{len(list_c)},收件人列表:{list_c}") # Outlook实例初始化移到循环外,仅执行一次 outlook=win32.Dispatch('outlook.application') for i in list_c: try: dt2 = dtest[dtest['Email_id']==i] # 修正HTML结构错误 body=f''' <html> <head></head> <body> <p>Hello All,<br> <p> Please submit your timesheet by eod.<br> {dt2.to_html()}<br> <font color ='blue'> <br>Thanks </font> <br><br> <font color ='red'> please note this is an automated mail do not reply </font> </p> </body> </html> ''' mail=outlook.CreateItem(0) mail.Subject = ' -testing email notification' mail.To = i mail.HTMLBody = body # 修正方法名大小写,改为大写Send() mail.Send() print(f"已成功发送给:{i}") except Exception as e: # 打印报错但不终止循环,继续给下一个人发送 print(f"发送给{i}失败,报错信息:{str(e)}")
内容的提问来源于stack exchange,提问作者vithal n
相关产品推荐
相关产品推荐

