'''
2021-05-22
To Dead Code
previously named: iphone_notes_image_extractor


Created on Feb 24, 2018
@author: Brett Paufler
Copyright Brett Paufler


For use with iPhone emailed notes with attached images
    Extracts images and saves as png's
    Also, saves txt file version of email text

Place iPhone Note Emails in ./input directory
    text and images extracted to ./output


Highly specific to this problem
    However, cut and pasted most of logic from
        android_voice_mail
        so, there is conceptual overlap
'''

import email

from os import listdir
from os.path import join as path_join

#Hardwired directories in and out
dir_in = '.\\input\\'
dir_out = '.\\output\\'

#list of all the '.eml' files in input directory
email_file_list = [path_join(dir_in, f) for
                 f in listdir(dir_in)
                 if f.endswith('.eml')]

#The main workhorse loop
for eml in email_file_list:
    
    #Current file we are working on
    print eml
    
    #Splits the email up into text and image part
    msg = email.message_from_file(open(eml))
    attachments = msg.get_payload()#[01]
    text = str(attachments[0])
    images = attachments[1].get_payload()

    #Clean Text Up
    #Still get some errors if nada on next line
    #text = text.replace('=20\r\n', '')
    #text = text.replace('=20\n\r', '')
    text = text.replace('=20\n', '')
    #text = text.replace('=\r\n', '')
    #text = text.replace('=\n\r', '')
    text = text.replace('=\n', '')
    print text

    #Saves the text part of email
    save_name = eml.replace(dir_in, dir_out)
    save_name = save_name[:-4] + '.txt'
    with open(save_name, 'wb') as f:
            f.write(str(text))

    #First Packet Contains My Signoff (Love, Brett)
    #So, discarded
    images = images[1:]
    
    for n, image in enumerate(images):

        #Extract png img part
        img = image.get_payload(decode=True)

        #Save Image
        save_name = '%s_%02d.png' % (
            save_name[:-4], n)
        print save_name
        
        with open(save_name, 'wb') as f:
            f.write(img)

#And That's a Wrap       
print 'Exited Without Error'