Guest User

Untitled

a guest
May 23rd, 2018
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Copyright 2009 (C) Pierre Duquesne <stackp@online.fr>
  4. # Licensed under the BSD Revised License.
  5.  
  6. import imaplib
  7. import smtplib
  8. import sys
  9. import optparse
  10. import getpass
  11. import email.parser
  12.  
  13. USAGE="imapfwd [options] USERNAME IMAPHOST SMTPHOST DESTINATION"
  14.  
  15. def parse_args():
  16. "Parse command-line arguments."
  17. parser = optparse.OptionParser(usage=USAGE)
  18. parser.add_option('--pass', dest='password', default=None,
  19. help="imap password")
  20. parser.add_option('-p', dest='port', type='int', default=None,
  21. help="imap port")
  22. parser.add_option('--ssl', dest='ssl', default=False,
  23. action='store_true',
  24. help="use SSL for imap")
  25. parser.add_option('--prefix', dest='prefix', default=None,
  26. action='store',
  27. help="append a string to subject. ex: [box1]")
  28. options, remainder = parser.parse_args(sys.argv[1:])
  29. return options, remainder
  30.  
  31. options, args = parse_args()
  32. try:
  33. username = args[0]
  34. imaphost = args[1]
  35. smtphost = args[2]
  36. destination = args[3]
  37. except:
  38. print "Error: some arguments are missing. Try --help."
  39. print USAGE
  40. sys.exit(1)
  41.  
  42. # connect to imap
  43. print 'Connecting to %s as user %s ...' % (imaphost, username)
  44. if options.ssl:
  45. IMAP = imaplib.IMAP4_SSL
  46. else:
  47. IMAP = imaplib.IMAP4
  48. try:
  49. if options.port:
  50. imap_server = IMAP(imaphost, options.port)
  51. else:
  52. imap_server = IMAP(imaphost)
  53. if not options.password:
  54. options.password = getpass.getpass()
  55. imap_server.login(username, options.password)
  56. except Exception,e:
  57. print 'Error:', e; sys.exit(1)
  58.  
  59. # connect to smtp
  60. try:
  61. smtp_server = smtplib.SMTP(smtphost)
  62. except Exception, e:
  63. print 'Could not connect to', smtphost, e.__class__, e
  64. sys.exit(2)
  65.  
  66. # filter unseen messages
  67. imap_server.select("INBOX")
  68. resp, items = imap_server.search(None, "UNSEEN")
  69. numbers = items[0].split()
  70.  
  71. # forward each message
  72. sender = "%s@%s" % (username, imaphost)
  73. for num in numbers:
  74. resp, data = imap_server.fetch(num, "(RFC822)")
  75. text = data[0][1]
  76. if options.prefix:
  77. parser = email.parser.HeaderParser()
  78. msg = parser.parsestr(text)
  79. msg['Subject'] = options.prefix + msg['Subject']
  80. text = msg.as_string()
  81. smtp_server.sendmail(sender, destination, text)
  82. # Flag message as Seen (may have already been done by the server anyway)
  83. imap_server.store(num, '+FLAGS', '\\Seen')
  84.  
  85. imap_server.close()
  86. smtp_server.quit()
Add Comment
Please, Sign In to add comment