Halbheld

Auto-forward unread emails via IMAP/SMTP

Nov 11th, 2026
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import imaplib, smtplib, email
  3. from datetime import datetime
  4.  
  5. # --- KONFIGURATION ---
  6. IMAP_SERVER = "imap.server.invalid"
  7. IMAP_USER   = "[email protected]"
  8. IMAP_PASS   = "yxayxa"
  9.  
  10. SMTP_SERVER = "outgoing.server.invalid"
  11. SMTP_PORT   = 587
  12. SMTP_USER   = "[email protected]"
  13. SMTP_PASS   = "lrxlrx"
  14.  
  15. FORWARD_TO  = "[email protected]"
  16. # ----------------------
  17.  
  18.  
  19. def check_and_forward():
  20.     try:
  21.  
  22.         now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  23.  
  24.         mail = imaplib.IMAP4_SSL(IMAP_SERVER)
  25.         mail.login(IMAP_USER, IMAP_PASS)
  26.         mail.select("INBOX")
  27.  
  28.         status, messages = mail.search(None, 'UNSEEN')
  29.         email_ids = messages[0].split()
  30.  
  31.         # NEU: Kurze Rückmeldung bei jedem Durchlauf
  32.         print(f"[{now}] [*] Posteingang geprüft. Ungelesene Mails: {len(email_ids)}")
  33.  
  34.         if email_ids:
  35.             smtp = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
  36.             smtp.starttls()
  37.             smtp.login(SMTP_USER, SMTP_PASS)
  38.  
  39.             for e_id in email_ids:
  40.                 status, msg_data = mail.fetch(e_id, '(RFC822)')
  41.                 for response_part in msg_data:
  42.                     if isinstance(response_part, tuple):
  43.                         msg = email.message_from_bytes(response_part[1])
  44.                         del msg['Resent-To']
  45.                         msg['Resent-To'] = FORWARD_TO
  46.  
  47.                         smtp.sendmail(SMTP_USER, [FORWARD_TO], msg.as_string())
  48.                         print(f"[{now}] [+] Weitergeleitet: {msg.get('Subject', 'Kein Betreff')}")
  49.                         mail.store(e_id, '+FLAGS', '\\Seen')
  50.  
  51.             smtp.quit()
  52.  
  53.         mail.logout()
  54.     except Exception as e:
  55.         print(f"[{now}] [-] Fehler: {e}")
  56.  
  57. if __name__ == "__main__":
  58.     check_and_forward()
Advertisement
Add Comment
Please, Sign In to add comment