Skip to content

Instantly share code, notes, and snippets.

@jahendrie
Created February 2, 2017 14:34
Show Gist options
  • Save jahendrie/d44ebcaa6c2a5f049568f281cae9af3f to your computer and use it in GitHub Desktop.
Save jahendrie/d44ebcaa6c2a5f049568f281cae9af3f to your computer and use it in GitHub Desktop.
Extracts attachments (pictures) from email files
#!/usr/bin/env python
import sys, os
import base64
token = "X-Attachment-Id"
def print_usage():
print( "Usage: exatt.py [OPTION] EMAIL_FILES" )
def print_help():
print( "This script extracts attachments (ostensibly, pictures) from" )
print(".eml files (email) and saves them to the present working directory.")
print( "By default, they use their originally recorded filenames." )
def extract_attachments( fileName, data, numAttachments ):
working = data
for at in range( numAttachments ):
part = working.partition( token )
## Get the original name
origName = part[0].split( '\n' )[-4]
origName = origName.partition( "filename=\"" )[2].partition( "\"" )[0]
## Attachment data
aString = part[2].partition( '\n' )[2].partition( "--" )[0]
aData = base64.b64decode( aString )
## Write the data to disk using its original filename
fout = open( origName, "wb" )
fout.write( aData )
fout.close()
working = part[2]
def process( fileName ):
try:
print( os.path.abspath( fileName ))
fin = open( os.path.abspath( fileName), "r" )
data = fin.read()
fin.close()
numAttachments = data.count( token )
if numAttachments > 0:
data.replace( "\r\n", "\n", -1 )
data.replace( "\r", "\n", -1 )
extract_attachments( fileName, data, numAttachments )
except FileNotFoundError or PermissionError:
print( "WARNING: Could not open '%s' for reading" % fileName )
def main():
if len( sys.argv ) < 2:
print( "ERROR: Incorrect usage" )
print_usage()
sys.exit( 1 )
elif sys.argv[1] == "-h" or sys.argv[1] == "--help":
print_usage()
print_help()
sys.exit( 0 )
else:
for arg in sys.argv[1:]:
process( arg )
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment