You need to enable JavaScript to run this app. 使用Python操作Outlook批量添加BCC密送收件人报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Python操作Outlook批量添加BCC密送收件人报错如何解决

问题原因

你遇到的NameError: name 'olBCC' is not defined报错,是因为olBCC是Outlook的内置枚举常量,没有通过win32com导入常量模块的话,Python无法识别这个变量名。

该常量对应的实际数值为3,同类枚举值规则如下:

  • 1:对应普通收件人(To字段)
  • 2:对应抄送收件人(CC字段)
  • 3:对应密送收件人(BCC字段)

解决方案

只需要修改你批量添加收件人的循环逻辑,给每个新增的收件人设置Type属性即可,有两种实现方式:

方案1:直接使用枚举值(无需额外导包,推荐)

将原代码中添加收件人的部分:

for recipient in emails:
     mail.Recipients.Add(recipient)

替换为:

for recipient in emails:
    # Add方法返回新增的Recipient对象,直接修改其Type属性即可
    rec = mail.Recipients.Add(recipient)
    rec.Type = 3

方案2:导入win32com常量(代码可读性更高)

如果你后续需要用到更多Outlook内置常量,可以导入常量模块后使用olBCC变量:

  1. 在代码开头添加导入语句:
import win32com.client.constants
  1. 修改添加收件人的循环:
for recipient in emails:
    rec = mail.Recipients.Add(recipient)
    rec.Type = win32com.client.constants.olBCC

修改后完整代码

import win32com.client
from openpyxl import load_workbook
wb = load_workbook(filename = r"C:\file.xlsx")
sheets = wb.sheetnames

ws = wb[sheets[0]]
rows = ws.max_row
columns = ws.max_column
count = 0
emails = []

for row in range(1,rows):
    if count != 0:
        break
    for column in range(1,columns):
        if '@blah' in str(ws.cell(row,column).value):
           count = count+1
           email_column = column
           
for email_row in range(row,rows):
    email = str(ws.cell(email_row,email_column).value)
    if  email not in emails and ('None' not in email):
        if abs(int(ws.cell(email_row,6).value)) <5:
            emails.append(email)         

outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)

# 修改后的添加BCC收件人逻辑
for recipient in emails:
    rec = mail.Recipients.Add(recipient)
    rec.Type = 3

mail.Subject = 'hi'
email_body = ("Blah. Blah.") 
mail.Body = email_body
mail.Display(True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:54:01