通过Python Win32com从MS Outlook中检索没有传出电子邮件的天数

yzuktlbb  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(128)

我想知道我们哪天没发邮件。我在WinPython和MS Office 2019(outlook)中使用了以下代码:

import win32com.client
import datetime

# Create an instance of Outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# Access the inbox folder
inbox = outlook.GetDefaultFolder(5).Items

# Set to store sent dates
sent_dates = set()
start_date = datetime.date(2022, 1, 1)
end_date = datetime.date(2023, 1, 1)

i = 0
for email in inbox:
    if email.Class == 43 and email.SentOn.date() >= start_date and email.SentOn.date() <= end_date:
        sent_dates.add(email.SentOn.date())
    print("Email", i)
    i += 1

# Create a range of dates within the specified date range
date_range = set(
    datetime.date.fromordinal(day) for day in range(
        start_date.toordinal(), end_date.toordinal() + 1
    )
)

# Exclude weekends (Saturday and Sunday)
date_range = {
    date for date in date_range if date.weekday() not in [5, 6]
}

# Find the workdays when you didn't send emails
workdays_without_emails = date_range - sent_dates

# Print workdays without sent emails
print("Workdays without sent emails:")
for day in sorted(workdays_without_emails):
    print(day)

当我在客户端工作一年,其余时间在Exchange服务器工作时,它就可以工作了。然后,当我下载2年的电子邮件,我再次运行,但现在这个错误时,它达到约6600电子邮件:

Traceback (most recent call last):
  File "C:\Users\xxxx\Downloads\WPy64-31150\scripts\outlook2.py", line 13, in <module>
    if correo.Class == 43 and correo.SentOn.date() >= start_date and correo.SentOn.date() <= end_date:
  File "C:\Users\xxxx\Downloads\WPy64-31150\python-3.11.5.amd64\Lib\site-packages\win32com\client\dynamic.py", line 627, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
pywintypes.com_error: (-2147352567, 'An exception occurred.', (4096, 'Microsoft Outlook', 'The underlying security system cannot find the name of the digital identifier.', None, 0, -2146893792), None)

当我尝试使用一年的电子邮件时,权限问题没有出现。

Email 6624
Email 6625
Email 6626
Email 6627
Traceback (most recent call last):
  File "C:/Users/xxx/Downloads/WPy64-31150/scripts/outlook3.py", line 17, in <module>
    if email.Class == 43 and email.SentOn.date() >= start_date and email.SentOn.date() <= end_date:
  File "C:\Users\xxx/Downloads\WPy64-31150\python-3.11.5.amd64\Lib\site-packages\win32com\client\dynamic.py", line 627, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
pywintypes.com_error: (-2147352567, 'An exception occurred.', (4096, 'Microsoft Outlook', 'The underlying security system cannot find the name of the digital identifier.', None, 0, -2146893792), None)

有什么建议吗?

4c8rllxm

4c8rllxm1#

迭代Inbox文件夹中的所有项目并不是一个好主意:

for email in inbox:
    if email.Class == 43 and email.SentOn.date() >= start_date and email.SentOn.date() <= end_date:
        sent_dates.add(email.SentOn.date())

相反,你可以每天/每周/每月运行一个过滤器来查找没有发送电子邮件的天数/周数/月数。在我十多年前为技术博客撰写的文章中,阅读更多关于Items类的Find/FindNextRestrict方法的信息:

相关问题