英文:
How do I resolve the following error: AttributeError: GetNamespace.GetNamespace - when connecting to Outlook using Python?
问题
以下是您提供的Python代码的翻译部分:
我编写了一些Python代码,执行以下操作:
- 连接到Outlook和特定子文件夹。
- 从用户获取目标日期。
- 搜索所有标记为“report.csv”的带附件的电子邮件,使用指定的目标日期。
- 删除/去除电子邮件主题中的某些关键词。
- 提取附件。
- 以电子邮件的解析主题保存附件到指定文件夹。
我的代码按照描述的方式工作,但在遍历电子邮件(或日期)时似乎会崩溃,只提取了我需要的30个左右报告中的4个。 以下是代码的副本。
当它崩溃时,VS Code 告诉我问题出在第54行的“outlook.GetNamespace.Quit()”,并建议说它是“AttributeError: GetNamespace.Getnamespace”。
对于此问题的任何想法和见解,将不胜感激。
英文:
I wrote some python code that does the following:
- connects to outlook and a specific subfolder
- gets a target date from the user
- searches all emails with attachments labeled "report.csv" using the specified target date
- removes/strips certain keywords in the subject of the email
- extracts the attachment
- saves the attachment with the parsed subject of the email in a specified folder
My code works as described but seems to crash when it iterates through the emails (or maybe dates), only extracting 4 out of the 30 or so reports I need. A copy of the code is below.
When it crashes, Vs Code is telling me the issue is on line 54 "outlook.GetNamespace.Quit()" and advising that it is "AttributeError: GetNamespace.Getnamespace"
Any thoughts and insight into this issue, would be greatly appreciated.
import os
import win32com.client
import datetime as dt
from datetime import date, timedelta
from pathlib import Path
EMAIL_ADDRESS = "emailaddress@example.com"
FOLDER_NAME = "subfolder_name"
OUTPUT_FOLDER = Path(r"Specify Path") #specify the path
def connect_to_outlook():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace ("MAPI")
inbox_folder = outlook.GetDefaultFolder(6) # Inbox folder
sub_folder = inbox_folder.Folders(FOLDER_NAME)
return sub_folder, outlook, inbox_folder, outlook
def extract_csv_attachments(emails):
csv_attachments = [(email.Subject.split("[INSERT TEXT TO PARSE/SPLIT")[0].strip(), attachment)
for email in emails
for attachment in email.Attachments if attachment.FileName == "report.csv"]
return csv_attachments
try:
# Connect to Outlook
sub_folder, outlook, inbox_folder, outlook = connect_to_outlook()
# Get target date from user input
target_date_str = input("Enter a target date (YYYY-MM-DD): ")
target_date = dt.datetime.strptime(target_date_str, '%Y-%m-%d')
# Construct search criteria and filter emails
search_criteria = f'[SenderEmailAddress] = "{EMAIL_ADDRESS}" AND [ReceivedTime] >= "{target_date.strftime("%m/%d/%Y")}" AND [ReceivedTime] < "{(target_date + dt.timedelta(days=1)).strftime("%m/%d/%Y")}"'
filtered_emails = sub_folder.Items.Restrict(search_criteria)
# Extract CSV attachments from filtered emails
csv_attachments = extract_csv_attachments(filtered_emails)
# Save extracted attachments to output folder
for email_subject, attachment in csv_attachments:
attachment.SaveAsFile(OUTPUT_FOLDER / f"{email_subject}.csv")
finally:
# Release Outlook resources
sub_folder = None
inbox_folder = None
outlook.GetNamespace.Quit()
outlook.Quit()
答案1
得分: 0
英文:
The Namespace class from the Outlook object model doesn't provide the Quit
method.
You may use the Application.Quit method which closes all currently open windows. In that case the associated Outlook session is closed completely; the user is logged out of the messaging system and any changes to items not already saved are discarded.
答案2
得分: 0
请使用Application.Quit
方法 - 没有Namespace.Quit
方法。
另外,请注意,大多数最终用户不希望Outlook突然关闭:Outlook是一个单例,创建Outlook.Application
对象的实例将返回指向已经运行的实例的指针。如果是您的代码创建了Outlook.Application
对象,就没有理由调用Application.Quit
- 只要您的代码引用消失,Outlook就会退出。如果您真的想关闭它,请至少检查确保Application.Explorers.Count == 0
和Application.Inspectors.Count == 0
,以确保没有用户打开的窗口。
英文:
Use Application.Quit
method - there is no Namespace.Quit
method.
Also keep in mind that most end users won't appreciate their Outlook closing on them: Outlook is a singleton, and creating an instance of the Outlook.Application
object will return a pointer to the already running instance. If it is your code that created Outlook.Application
object, there is no reason to call Application.Quit
- Outlook will exit when your code reference to it is gone. If you really want to close it, at least check to make sure that both Application.Explorers.Count == 0
and Application.Inspectors.Count == 0
to ensure there are no open windows opened by the user.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论