inject: Decode subject line before storing the email.
[patchq.git] / inject-mbox.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Inject one or more mbox of email, or a single email into the system.
5 #
6 # ./inject-mbox.py mbox [mbox ...]
7 # ./inject-mbox.py < single_email
8 #
9 # Note that if you inject the same message or message threads twice,
10 # then they are processed twice.  patchq does not deduplicate.
11 #
12 # This script will inject anything that looks similar enough to an
13 # email, even non-patches, cover letters, etc.  The ‘threader.py’
14 # script filters out non-patches.
15
16 import email
17 import mailbox
18 import pika
19 import sys
20 import config
21
22 connection = pika.BlockingConnection(pika.ConnectionParameters(
23     host = config.mq_server))
24 channel = connection.channel()
25
26 processed = 0
27
28 def inject(m):
29     global processed
30
31     # Decode the subject line and store it back in the email as UTF-8.
32     # This saves a lot of effort later on, even though it's not
33     # strictly RFC822 compliant.
34     # https://stackoverflow.com/questions/7331351/python-email-header-decoding-utf-8/7331577#7331577
35     subj = m['Subject']
36     subj = email.header.decode_header(subj)
37     subj = ''.join([ unicode(t[0], t[1] or 'ASCII') for t in subj ])
38     m['Subject'] = subj
39
40     print("Injecting %s" % m['Subject'])
41
42     channel.basic_publish(exchange = 'patchq_input',
43                           routing_key = '',
44                           body = m.as_string())
45     processed = processed+1
46
47 # Read from mboxes passed on the command line, or read a single
48 # email from stdin.
49 if len(sys.argv) > 1:
50     for arg in sys.argv[1:]:
51         mbox = mailbox.mbox(arg)
52         for m in mbox:
53             inject(m)
54 else:
55     m = email.message_from_file(sys.stdin)
56     inject(m)
57
58 print ("Processed %d email(s)." % processed)