Ungefähr so.
Zeilen 9-11 anpassen und in Zeile 66 definieren welche Mails wohin verschoben werden sollen.
import imaplib
import email
from email.header import decode_header
import re # For pattern matching, if needed
import time
import datetime
# Define connection parameters
IMAP_SERVER = "IP ADDRESS"
EMAIL_ACCOUNT = "SERVER\USER"
PASSWORD = "PASSWORD"
def connect_to_imap():
# Connect to the IMAP server and log in
try:
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL_ACCOUNT, PASSWORD)
print("Connected to IMAP server.")
return mail
except imaplib.IMAP4.error as e:
print("IMAP login failed:", e)
return None
def search_emails(mail, criteria):
# Search for emails based on the specified criteria
try:
mail.select("inbox") # Connect to inbox
status, message_ids = mail.search(None, criteria)
if status != "OK":
print("No messages found!")
return []
return message_ids[0].split() # List of message IDs
except imaplib.IMAP4.error as e:
print("Error searching emails:", e)
return []
def move_email(mail, msg_id, destination_folder):
# Move an email to the destination folder
try:
result = mail.copy(msg_id, destination_folder)
if result[0] == 'OK':
mail.store(msg_id, '+FLAGS', '\\Deleted')
mail.expunge() # Remove marked emails
print(f"Email ID {msg_id.decode()} moved to {destination_folder}.")
else:
print(f"Failed to move email ID {msg_id.decode()}.")
except imaplib.IMAP4.error as e:
print("Error moving email:", e)
def find_and_move(mail, criteria, target_folder):
message_ids2 = search_emails(mail, criteria)
print(f"Moving {criteria} matching email(s).")
print(f"Found {len(message_ids2)} matching email(s).")
for msg_id in message_ids2:
move_email(mail, msg_id, target_folder)
def main():
# Connect to the server
mail = connect_to_imap()
if mail is None:
return
find_and_move(mail, '(FROM "
sender@something.com") (SUBJECT "Something")', "INBOX.SubFolder1.SubFolder2" )
mail.expunge()
mail.close()
mail.logout()
print("Disconnected from IMAP server.")
if __name__ == "__main__":
main()