Skip to content

Instantly share code, notes, and snippets.

@mcm
Last active December 27, 2015 03:09
Show Gist options
  • Save mcm/7257631 to your computer and use it in GitHub Desktop.
Save mcm/7257631 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import imaplib
import optparse
import subprocess
import sys
op = optparse.OptionParser()
op.add_option("--username", dest="username", help="IMAP username")
op.add_option("--password", dest="password", help="IMAP password")
op.add_option("--mailgate", dest="mailgate", help="Path to rt-mailgate")
op.add_option("--url", dest="url", help="RT URL")
(options, args) = op.parse_args()
def exit_with_error(message=None):
if message:
sys.stderr.write("{}\n".format(message))
sys.exit(2)
imaps = imaplib.IMAP4_SSL("imap.gmail.com")
# Log into IMAP account
result = imaps.login(options.username, options.password)
if result[0] != "OK":
exit_with_error("Unable to login to mail server")
# List subfolders
result = imaps.list("rt")
for mailbox in result[1]:
mbox = mailbox.split()[2].strip('"')
if mbox == "rt":
continue
try:
_,queue,action = mbox.split("/")
except ValueError:
_,queue = mbox.split("/")
action = "correspond"
RT_MAILGATE = "{} --url {} --queue {} --action {}".format(options.mailgate, options.url, queue, action)
imaps.select(mbox)
_,result = imaps.search(None, "(UNSEEN)")
for idx in result[0].split():
_,message = imaps.fetch(idx, '(RFC822)')
mg = subprocess.Popen(RT_MAILGATE.split(" "), stdin=subprocess.PIPE, stdout=None)
mg.stdin.write(message)
mg.stdin.close()
imaps.store(idx, "+FLAGS", r"\Seen")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment