Forwarding an email with python smtplib

Posted by robbles on Stack Overflow See other posts from Stack Overflow or by robbles
Published on 2010-04-26T21:54:34Z Indexed on 2010/04/26 22:33 UTC
Read the original article Hit count: 462

Filed under:
|
|
|
|

I'm trying to put together a script that automatically forwards certain emails that match a specific criteria to another email.

I've got the downloading and parsing of messages using imaplib and email working, but I can't figure out how to forward an entire email to another address. Do I need to build a new message from scratch, or can I somehow modify the old one and re-send it?

Here's what I have so far (client is an imaplib.IMAP4 connection, and id is a message ID):

status, data = client.fetch(id, '(RFC822)')
email_body = data[0][1]
mail = email.message_from_string(email_body)

# ...Process message...

# This doesn't work
forward = email.message.Message()
forward.set_payload(mail.get_payload())
forward['From'] = '[email protected]'
forward['To'] = '[email protected]'

smtp.sendmail(user, ['[email protected]'], forward.as_string())

I'm sure there's something slightly more complicated I need to be doing with regard to the MIME content of the message. Surely there's some simple way of just forwarding the entire message though?

# This doesn't work either, it just freezes...?
mail['From'] = '[email protected]'
mail['To'] = '[email protected]'
smtp.sendmail(user, ['[email protected]'], mail.as_string())

© Stack Overflow or respective owner

Related posts about python

Related posts about smtplib