开发Python程序实现共享Outlook收件箱邮件分类迁移功能
For handling shared inbox emails with the ABC-***** classifier, the exchangelib library is an excellent choice—it provides a straightforward way to interact with Exchange/Outlook mailboxes, including shared ones. Below is a complete, production-ready script that covers all your requirements:
Step 1: Install Required Library
First, install exchangelib if you haven't already:
pip install exchangelib
Step 2: Full Python Script
import re import os from exchangelib import Credentials, Account, Folder def get_or_create_folder(parent_folder, folder_name): """Retrieve an existing folder or create a new one if it doesn't exist""" try: # Check if the folder exists under the parent folder_path = parent_folder / folder_name if not folder_path.exists(): # Create the folder if it doesn't exist new_folder = Folder(parent=parent_folder, name=folder_name) new_folder.save() print(f"Created new folder: {folder_name}") return new_folder return folder_path except Exception as e: print(f"Error accessing/creating folder '{folder_name}': {str(e)}") return None def process_shared_inbox(): # Configure credentials (use secure methods in production!) # For Alteryx, consider using environment variables or Alteryx's credential manager credentials = Credentials( username=os.getenv("EMAIL_USERNAME", "your_user@domain.com"), password=os.getenv("EMAIL_PASSWORD", "your_password") ) # Connect to the shared mailbox try: account = Account( primary_smtp_address="shared_inbox@domain.com", credentials=credentials, autodiscover=True, access_type="delegate" ) print(f"Successfully connected to shared inbox: {account.primary_smtp_address}") except Exception as e: print(f"Failed to connect to mailbox: {str(e)}") return # Regex pattern to match the ABC-***** classifier # Adjust the pattern if your classifier has different characters/length classifier_pattern = re.compile(r"ABC-[A-Z0-9]{5}", re.IGNORECASE) # Get the shared inbox folder inbox = account.inbox # Process emails (filter to unread if desired: inbox.filter(is_read=False)) for email in inbox.all().order_by("-datetime_received"): classifier = None # Check subject first for the classifier subject_match = classifier_pattern.search(email.subject) if subject_match: classifier = subject_match.group().upper() else: # Check email body if not found in subject body_match = classifier_pattern.search(email.body) if body_match: classifier = body_match.group().upper() if classifier: target_folder = get_or_create_folder(inbox, classifier) if target_folder: try: # Move the email to the target folder email.move(target_folder) print(f"Moved email: '{email.subject}' -> Folder: '{classifier}'") # Optional: Mark email as read after processing # email.is_read = True # email.save() except Exception as e: print(f"Failed to move email '{email.subject}': {str(e)}") if __name__ == "__main__": process_shared_inbox()
Key Details & Customization Tips
- Regex Pattern: The pattern
ABC-[A-Z0-9]{5}matches exactly 5 alphanumeric characters afterABC-. Adjust the{5}to match your classifier's length, or modify[A-Z0-9]if your classifier includes other characters (e.g., underscores). - Security: Never hardcode credentials! Use environment variables (as shown) or Alteryx's built-in credential manager to store sensitive information securely.
- Email Filtering: The script processes all emails in the inbox. To only process unread emails, replace
inbox.all()withinbox.filter(is_read=False). - Folder Handling: Folders are created directly under the shared inbox and are case-normalized (using
.upper()) to avoid duplicate folders with different capitalization. - Alteryx Integration:
- Ensure
exchangelibis installed in your Alteryx Python environment (use a "Run Command" tool to executepip install exchangelibif needed). - Use Alteryx's scheduling feature to run the script at your desired interval (hourly, daily, etc.).
- Pass credentials securely using Alteryx's "Text Input" or "Credential" tools instead of hardcoding.
- Ensure
Troubleshooting Notes
- If you get authentication errors, verify that your account has delegate access to the shared mailbox.
- Autodiscover issues? Check that your Exchange server allows autodiscover, or manually specify the server URL in the
Accountsetup.
内容的提问来源于stack exchange,提问作者Orbanez
相关产品推荐
相关产品推荐

