使用Python调用Outlook批量发邮件,如何规避保护级别确认或设置默认级别?
问题:Python批量发送Outlook邮件时的保护级别弹窗问题
原代码
import win32com.client as win32 import datetime import os for i in range(3): outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.Subject = 'test ' + datetime.now().strftime('%#d %b %Y %H:%M') mail.To = "example@example.com" # attachment = mail.Attachments.Add(os.getcwd() + "\\") # attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "currency_img") mail.HTMLBody = r""" Dear Carrie,<br><br> The highlighted of currencies exchange prices is as follow:<br><br> <img src="cid:currency_img"><br><br> For more details, you can check the table in the Excel file attached.<br><br> Best regards,<br> Yeung """ mail.Attachments.Add(os.getcwd() + "\\example.xlsx") mail.Send()
问题描述
使用上述代码批量发送邮件时,每次循环Outlook都会弹出保护级别确认窗口(如下图),希望能规避该确认步骤,或设置默认保护级别为“公开(Öffentlichkeit)”。

解决方案
方法1:将Python程序添加到Outlook信任中心
- 打开Outlook,依次点击「文件」→「选项」→「信任中心」→「信任中心设置」
- 选择「程序访问和加载项」,点击「添加」,找到你的Python可执行文件(如
python.exe或pythonw.exe) - 将该程序设置为「始终允许」,保存设置后重启Outlook
方法2:使用Redemption库绕过安全提示
Redemption是专门规避Outlook安全限制的第三方库,操作步骤:
- 安装库:
pip install redemption - 修改代码替换原Outlook调用逻辑:
import win32com.client as win32 import datetime import os import redemption for i in range(3): rdoSession = redemption.RDOSession() rdoSession.Logon() # 使用当前Outlook配置文件登录 mail = rdoSession.CreateItem(0) mail.Subject = 'test ' + datetime.now().strftime('%#d %b %Y %H:%M') mail.To = "example@example.com" mail.HTMLBody = r""" Dear Carrie,<br><br> The highlighted of currencies exchange prices is as follow:<br><br> <img src="cid:currency_img"><br><br> For more details, you can check the table in the Excel file attached.<br><br> Best regards,<br> Yeung """ mail.Attachments.Add(os.getcwd() + "\\example.xlsx") mail.Send() rdoSession.Logoff()
方法3:通过注册表设置默认保护级别
注意:修改注册表有风险,请先备份注册表再操作
- 按下Win+R,输入
regedit打开注册表编辑器 - 定位到对应路径:
HKEY_CURRENT_USER\Software\Microsoft\Office\<你的Outlook版本>\Outlook\Security
(例如Outlook 2019对应路径为HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Security) - 右键新建「DWORD(32位)值」,命名为
DefaultSecurityLevel - 设置数值数据为
0(对应“公开”级别),确定后重启Outlook
方法4:在代码中直接设置邮件安全属性
在原代码的mail.Send()之前添加以下代码,直接指定邮件保护级别:
# 设置邮件保护级别为公开(0=公开,1=内部,2=机密,3=绝密) mail.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x6E010003", 0)
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

