How do I resolve the following error: AttributeError: GetNamespace.GetNamespace – when connecting to Outlook using Python?

huangapple go评论59阅读模式
英文:

How do I resolve the following error: AttributeError: GetNamespace.GetNamespace - when connecting to Outlook using Python?

问题

以下是您提供的Python代码的翻译部分:

我编写了一些Python代码,执行以下操作:

  1. 连接到Outlook和特定子文件夹。
  2. 从用户获取目标日期。
  3. 搜索所有标记为“report.csv”的带附件的电子邮件,使用指定的目标日期。
  4. 删除/去除电子邮件主题中的某些关键词。
  5. 提取附件。
  6. 以电子邮件的解析主题保存附件到指定文件夹。

我的代码按照描述的方式工作,但在遍历电子邮件(或日期)时似乎会崩溃,只提取了我需要的30个左右报告中的4个。 以下是代码的副本。

当它崩溃时,VS Code 告诉我问题出在第54行的“outlook.GetNamespace.Quit()”,并建议说它是“AttributeError: GetNamespace.Getnamespace”。

对于此问题的任何想法和见解,将不胜感激。

英文:

I wrote some python code that does the following:

  1. connects to outlook and a specific subfolder
  2. gets a target date from the user
  3. searches all emails with attachments labeled "report.csv" using the specified target date
  4. removes/strips certain keywords in the subject of the email
  5. extracts the attachment
  6. 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 == 0Application.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.

huangapple
  • 本文由 发表于 2023年5月18日 02:08:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定