Email and attachement to facebook post
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I am looking for a way to have emails that are from a specific email address, posted to my Facebook.
The email will contain some text, and a few attached photos, possibly a short video.

which mail provider r u using? and what programming language r u using?Thanks
Codeword 25 days ago
I will be using gmail. This will be a stand alone program. I would prefer it to run on a my server. I use DreamHost and their server runs Python v2.7.6 I am also open to have it run on a laptop running windows 7 or greater.
Wcubed 25 days ago
For my clarification Do you want something like this. A python script read email from your Gmail and then if the email is from the specificified email address, you want to post the content of that email to your facebook. Is this what you want? I am getting it right? Thank you, Wcubed.
Codeword 25 days ago
Yes. You are getting it right. But it is important that the attached photos and video will be posted as well. There is an extra $5 if the subject of the email is the album the photos are posted to.
Wcubed 25 days ago
okay got it.Thank you
Codeword 25 days ago
update: I have successfully prepared the code that will fetch specified emails from your Gmail and also save their attachments. IMPORTANT: we will first need to save the attached images in our local computer first, then we will have to post the attached emails+pic to facebook. Reason: is that we cannot directly post the links of the attachement sent in gmail.That's why we have to save it first and then post it to facebook.com I am preparing the rest of the code and in the meanwhile let me know your thoughts.Thank you
Codeword 24 days ago
As long as everything is fully automated I am okay with it being saved locally. Can the attachment be pulled from the email into Google Drive then posted to FB? This way I do not need to have a dedicated machine. Thank you
Wcubed 24 days ago
No, even if try to send the images to google drive and then post from there you will first need to get the shareable link manually and all that.So you will have to first store on local computer and then upload to facebook.com.If you are concerned about the space consumption then we can delete the pics once we have successfully posted to facebook.com using python. :)
Codeword 24 days ago
I am not worried about the space. My only requirement is that it is all automated. I have an old computer that can be dedicated to the task. But I will not be around to handle any of the tasks.
Wcubed 24 days ago
Okay, Wcubed, one more thing I wanted to ask you, do you want to post to a facebook page or to a profile.Thank you.
Codeword 24 days ago
The profile please. I may want a page later on, but for now I prefer it going directly to my profile. Thank you
Wcubed 24 days ago
UPDATE : I have just completed the code and after a little testing I will upload my solution shortly.Thank you
Codeword 24 days ago
awarded to Codeword

Crowdsource coding tasks.

1 Solution


Here is the code.
The code mainly has 2 parts Grabbing unread emails and Posting the subject+body+images to facebook

Here how it works

step1 Create a facebook app and get the access token with the necessary permission to upload photos by going over to graph api tool in the developer console of facebook https://developers.facebook.com/tools/explorer/129043021099215?method=GET&path=me%3Ffields%3Did%2Cname&version=v2.11

step2 ** Create a folder named **emails in the same directory as the python file.

** Step3** Set this variables in the python file

gmail_user = 'my_username'  # your gmail username
gmail_pwd = 'my_pwd'  # your gmail password
interested_email = test@gmail.com'  # the email from the specific sender you are interested in
root = './emails/'    # the root folder which stores emails and their data

no_days_query = 1  # fetch unread emails sent 1 day ago to present

# your facebook app access token
access_token="EAAB1XStu8M8BAKBlacjB3AzBvl4w1jravYxzXuwqPMzIMZBvmf2ZBbjwCZCdewzWAZBQqWdYdYjXIH1Aelkd0VjxNIZCLQ9GNK8YpdrpnfZBu8EuFIp5JISXZCmsvurBaW2Wo4i77v0uZC1g9Obu6CsOTYPU0YrV4nf7fQZCwGZAdZAqT59JOGHsVfm"

Note be sure to check the checkboxes in a similar way like this https://drive.google.com/open?id=0Bycm505pe6VGbmExekNSTUlVUTg when you create the access token to avoid permission error

Code

def main():
    pass

if __name__ == '__main__':
    main()


import sys
from datetime import datetime, timedelta
import os
import imaplib
import email
import facebook



# # Read only emails from last 1 days
no_days_query = 1
detach_dir = '.'

if 'emails' not in os.listdir(detach_dir):
    os.mkdir('emails')

server = "imap.gmail.com"
port_num = 993

def post_on_fb(imgs_list, msg):
    # use your access token
    graph = facebook.GraphAPI(
        access_token="EAAB1XStu8M8BAKBlacjB3AzBvl4w1jravYxzXuwqPMzIMZBvmf2ZBbjwCZCdewzWAZBQqWdYdYjXIH1Aelkd0VjxNIZCLQ9GNK8YpdrpnfZBu8EuFIp5JISXZCmsvurBaW2Wo4i77v0uZC1g9Obu6CsOTYPU0YrV4nf7fQZCwGZAdZAqT59JOGHsVfm",
        version="2.1")

    imgs_id = []
    for img in imgs_list:
        photo = open(img, "rb")
        imgs_id.append(graph.put_photo(photo, album_id='me/photos', published=False)['id'])
        photo.close()

    args = dict()
    args["message"] = 'Subject : '+ msg[0]+'\nContent : '+msg[0]
    for img_id in imgs_id:
        key = "attached_media[" + str(imgs_id.index(img_id)) + "]"
        args[key] = "{'media_fbid': '" + img_id + "'}"

    graph.request(path='/me/feed', args=None, post_args=args, method='POST')


def read_email(gmail_user, gmail_pwd, interested_email):

    conn = imaplib.IMAP4_SSL(server, port_num)
    conn.login(gmail_user, gmail_pwd)
    conn.select()

    #Check status for 'OK'
    status, all_folders = conn.list()

    folder_to_search = 'INBOX'
    #folder_to_search = '[Google Mail]/All Mail'

    #Check status for 'OK'
    status, select_info = conn.select(folder_to_search)
    if status == 'OK':
        today = datetime.today()
        cutoff = today - timedelta(days=no_days_query)
        #this search key tell the program to search of the specified email and fetch the content only if the email has not been read yet.
        search_key = interested_email + " after:" + cutoff.strftime('%Y/%m/%d') + 'has:attachment in:unread'
        status, message_ids = conn.search(None, 'X-GM-RAW', search_key)#X-GM-RAW
        for id in message_ids[0].split():
            status, data = conn.fetch(id, '(RFC822)')
            email_msg = email.message_from_string(data[0][1])
            #Print all the Attributes of email message like Subject,
            message_id = email_msg['Message-ID']
            message_id = message_id[1:len(message_id)-1]
            subject = email_msg['Subject']
            #sender_email = email_msg['From']
            #sent_to_email = email_msg['To']
            if message_id not in os.listdir('./emails'):
                os.mkdir('./emails/'+message_id)
            for part in email_msg.walk():
                if part.get_content_type() == 'text/plain':
                    email_content = part.get_payload()# prints the raw text
                filename = part.get_filename()
                if bool(filename):
                    filepath = os.path.join(detach_dir, 'emails\\'+message_id, filename)
                    if not os.path.isfile(filepath):
                        fp = open(filepath, 'wb')
                        fp.write(part.get_payload(decode=True))
                        fp.close()

                    # out = csv.writer(open(detach_dir+'/emails/'+message_id+'/message_id'+'.', "wb"), delimiter=',', quoting=csv.QUOTE_ALL)
                    # out.writerow([subject,email_content])
                    out = open(detach_dir+'/emails/'+message_id+'/'+message_id+'.txt', "w")
                    out.write(subject+'::::'+email_content)
                    out.close()

    else:
        print "Error"

if __name__ == '__main__':
    # Gmail Configuration
    gmail_user = 'your_email'
    gmail_pwd = 'your_pass'
    interested_email = 'specific_email_ur_interested_in'
    ret = read_email(gmail_user, gmail_pwd, interested_email)
    root = './emails/'
    dirlist = [item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item))]
    for directory in dirlist:
        dir_path = os.path.join(detach_dir, 'emails\\'+directory)
        txt_path = os.path.join(detach_dir, 'emails\\'+directory+'\\'+directory+'.txt')
        img_list = []
        msg = []
        for filename in os.listdir(dir_path):
            if filename.endswith(".jpg") or filename.endswith(".png"):
                #print(os.path.join(dir_path, filename))
                img_list.append(os.path.join(dir_path, filename))
            elif filename.endswith(".txt"):
                file_cont = open(txt_path,'r')
                msg = file_cont.read().split('::::')
            else:
                pass

        post_on_fb(img_list, msg)

you can install the facebook python sdk from here
http://facebook-sdk.readthedocs.io/en/latest/api.html

pip install facebook-sdk

Thank you