Skip to content

Instantly share code, notes, and snippets.

@tom-ficke
Last active January 4, 2019 18:58
Show Gist options
  • Save tom-ficke/7b3f7639c76c64b8358c96549a45709b to your computer and use it in GitHub Desktop.
Save tom-ficke/7b3f7639c76c64b8358c96549a45709b to your computer and use it in GitHub Desktop.
Script to Read Messages in IMAP Inbox & Forward to Another Email Address
#!/usr/bin/env python
#
# Script to Read Messages in IMAP Inbox & Forward to Another Email Address
#
# Script Created from :
# http://codehandbook.org/how-to-read-email-from-gmail-using-python/
# https://stackoverflow.com/questions/2717196/forwarding-an-email-with-python-smtplib
import smtplib
import imaplib
import email
MAIL_SERVER = "##########"
MAIL_LOGIN = "##########"
MAIL_PASS = "##########"
ADDR_FROM = "##########"
ADDR_TO = "##########"
try:
mail = imaplib.IMAP4_SSL(MAIL_SERVER)
mail.login(MAIL_LOGIN,MAIL_PASS)
mail.select('inbox')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
# Read List of Message and Forward Messages to ADDR_TO
for i in range(latest_email_id,first_email_id, -1):
typ, data = mail.fetch(i, '(RFC822)' )
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
msg.replace_header("From", ADDR_FROM)
msg.replace_header("To", ADDR_TO)
email_subject = msg['subject']
smtp = smtplib.SMTP(MAIL_SERVER, 587)
smtp.starttls()
smtp.login(MAIL_LOGIN, MAIL_PASS)
smtp.sendmail(ADDR_FROM, ADDR_TO, msg.as_string())
smtp.quit()
print 'Forwarding Message Subject : ' + email_subject + '\n'
# Move Message Trash and Remove Message
MOVE_TO_TRASH = mail.uid('COPY', i, "Inbox.Trash")
if MOVE_TO_TRASH[0] == 'OK':
mail.store(i, "+FLAGS", '(\\Deleted)')
#mail.expunge()
print 'Deleting Message'
except Exception, e:
print str(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment