Сохранение писем из OutlookPython

Программы на Python
Ответить
Anonymous
 Сохранение писем из Outlook

Сообщение Anonymous »

С помощью ChatGPT я написал код, который сохраняет все активные электронные письма из Outlook в папку с датой и темой электронного письма. Работает довольно хорошо, но некоторые сбои я не могу объяснить.
Код сохраняет электронное письмо и папку, а затем помещает электронное письмо в папку.
И в этот момент в некоторых случаях появляется ошибка о том, что папка/путь не существует, даже если она существует. Я думал, что это может быть из-за того, что длина пути превышает предел в 260, но затем я попробовал тестовое электронное письмо с гораздо более длинной темой, и оно все равно сработало. Код также удаляет все символы, которые могут вызывать появление имени файла в Windows.

Имеете ли вы представление о том, о чем эти сбои?
Код:

Код: Выделить всё

import os
import shutil
import re
import datetime
import win32com.client
import win32timezone
import win32file  # Importiere pywin32 für das Verschieben von Dateien

def clean_filename(filename):
"""Replaces invalid characters in the filename and removes duplicate spaces."""
invalid_chars = r'\\/:*?"|'
for char in invalid_chars:
filename = filename.replace(char, '')  # Entfernt ungültige Zeichen

# Replace multiple spaces with a single space
filename = re.sub(r'\s+', ' ', filename)

filename = filename.strip()  # Entfernt führende und nachfolgende Leerzeichen
if not filename:
filename = "Unbenannte_E-Mail"
return filename

def move_file_windows(source, destination):
"""Verwendet win32file.MoveFile, um die Datei ähnlich wie Drag & Drop zu verschieben."""
try:
# Windows-spezifischer Move-Versuch
win32file.MoveFile(source, destination)
print(f"E-Mail erfolgreich verschoben: {destination}")
except Exception as e:
print(f"Fehler beim Verschieben der E-Mail mit pywin32: {e}")
# Fallback auf shutil.move falls es Probleme gibt
try:
shutil.move(source, destination)
print(f"E-Mail erfolgreich verschoben mit shutil: {destination}")
except Exception as e:
print(f"Fehler beim Verschieben mit shutil: {e}")

def save_emails():
# Get the directory where the Python or EXE file is stored
script_dir = os.path.dirname(os.path.realpath(__file__))

# Define the base folder for saving emails relative to the script directory
base_path = script_dir  # Use the directory where the script is located

# Check if base folder exists
if not os.path.exists(base_path):
print(f"Der Basisordner existiert nicht: {base_path}")
return

print(f"Base Path: {base_path}")

# Outlook application
outlook = win32com.client.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
active_explorer = outlook.ActiveExplorer()
selection = active_explorer.Selection

if len(selection) == 0:
print("Bitte wählen Sie mindestens eine E-Mail aus.")
return

# Sort emails by received time (ascending order, older emails first)
emails = sorted(selection, key=lambda item: item.ReceivedTime)

# Dictionary to track duplicates (key: date + subject, value: list of emails)
email_groups = {}

# Group emails by date and subject
for item in emails:
if item.Class == 43:  # Check if item is a MailItem
subject = clean_filename(item.Subject)
received_date = item.ReceivedTime
date_str = received_date.strftime('%Y.%m.%d')
folder_key = f"{date_str}_{subject}"

if folder_key not in email_groups:
email_groups[folder_key] = []
email_groups[folder_key].append(item)

# Process grouped emails
for folder_key, items in email_groups.items():
date_str, subject = folder_key.split("_", 1)

for idx, item in enumerate(items):
# Determine folder and file names
if len(items) >  1:  # Add counter if there are duplicates
counter = idx + 1
folder_name = f"{date_str}_{counter}_{subject}"
file_name = f"{counter}_{subject}.msg"
else:  # No counter if only one email with this subject and date
folder_name = f"{date_str}_{subject}"
file_name = f"{subject}.msg"

folder_name = folder_name.strip()
final_folder_path = os.path.join(base_path, folder_name)

# Check if folder exists, otherwise create it
try:
os.makedirs(final_folder_path, exist_ok=True)  # Ensure folder exists
print(f"Ordner erstellt: {final_folder_path}")
except Exception as e:
print(f"Fehler beim Erstellen des Ordners: {e}")
continue

temp_file_path = os.path.join(base_path, file_name)
final_file_path = os.path.join(final_folder_path, file_name)

# Save email
try:
item.SaveAs(temp_file_path, 3)  # 3 corresponds to olMsg format
print(f"Email gespeichert: {temp_file_path}")
except Exception as e:
print(f"Fehler beim Speichern der E-Mail: {e}")
continue

# Move the file to the new folder using pywin32
move_file_windows(temp_file_path, final_file_path)

if __name__ == "__main__":
save_emails()
input("Drücken Sie die Eingabetaste, um das Fenster zu schließen/Premere il tasto Invio per chiudere la finestra...")
Я пытался сохранить электронные письма в папках с указанием даты и темы. Это работало довольно хорошо, за исключением нескольких исключений, когда они не перетаскивались в нужную папку.

Подробнее здесь: https://stackoverflow.com/questions/793 ... om-outlook
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»