Created
October 11, 2012 13:58
-
-
Save Svenito/3872497 to your computer and use it in GitHub Desktop.
Parse email for image URL and process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python | |
import subprocess | |
import fileinput | |
import email | |
import re | |
def extract_body(payload): | |
if isinstance(payload,str): | |
return payload | |
else: | |
return '\n'.join([extract_body(part.get_payload()) for part in payload]) | |
def extract_image_urls(body): | |
match_http = re.compile('^http:i\/\/') | |
image_urls = [] | |
for line in body.split('\n'): | |
stripped_line = line.strip() | |
if len(stripped_line) == 0: | |
continue | |
m = re.search(r'^http:\/\/', stripped_line) | |
if m is None: | |
continue | |
m = re.search(r'\.(?:(jpg)|(png)|(gif)|(jpeg)|(tif))$', stripped_line, re.IGNORECASE) | |
if m is not None: | |
image_urls.append(stripped_line) | |
return image_urls | |
if __name__ == "__main__": | |
full_email = [] | |
for line in fileinput.input(): | |
full_email.append(line) | |
full_email = ''.join(full_email) | |
msg = email.message_from_string(full_email) | |
pl = msg.get_payload() | |
body = extract_body(pl).split('-- \n')[0] | |
image_urls = extract_image_urls(body) | |
for img in image_urls: | |
subprocess.call(['/path/to/script', img]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment