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):
import smtplib, imaplib
smtp = smtplib.SMTP(host, smtp_port)
smtp.login(user, passw)
client = imaplib.IMAP4(host)
client.login(user, passw)
client.select('INBOX')
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'] = 'source.email.address@domain.com'
forward['To'] = 'my.email.address@gmail.com'
smtp.sendmail(user, ['my.email.address@gmail.com'], 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'] = 'source.email.address@domain.com'
mail['To'] = 'my.email.address@gmail.com'
smtp.sendmail(user, ['my.email.address@gmail.com'], mail.as_string())
I think the part you had wrong was how to replace the headers in the message, and the fact that you don't need to make a copy of the message, you can just operate directly on it after creating it from the raw data you fetched from the IMAP server.
You did omit some detail so here's my complete solution with all details spelled out. Note that I'm putting the SMTP connection in STARTTLS mode since I need that and note that I've separated the IMAP phase and the SMTP phase from each other. Maybe you thought that altering the message would somehow alter it on the IMAP server? If you did, this should show you clearly that that doesn't happen.
Hope this helps even if this answer comes quite late.
In one application I download messages via POP3 (using poplib) and forward them using your second method... That is, I alter To/From on the original Message and send it, and it works.
Have you tried poking inside smtp.sendmail to see where it stops?