Esempio n. 1
0
    def getEmailImap(self, server):
        ''' getEmail(host_server):
        This module is a simple interface to check for new emails in the inbox of Gmail or CERN imap servers. 
        This is a simple example of how to use the IMAP protocol to receive emails. As I understand, the IMAP protocol is more involved in the python libraries 
        than the POP3 analogue, with more complicated/obscure modules. It does however offer a mean of accessing unread email, unlike the POP3 protocol for which I had to 
        create a time-stamp support to know when it was the last time I checked my inbox. Nevertheless, at present I prefer POP3.
        '''
        # Import modules here
        import python_myFunctions as myFunctions
        import imaplib
        import email
        import traceback
        import sys
        import getpass
        import time
        from datetime import datetime
        from dateutil import parser
        import os
        import pydoc

        # Declaration here
        f = myFunctions.CreateObject()
        newMailFiles = []
        myPath = "/Users/administrator/my_work/programming/python/inbox/" + server + "/imap/"

        # Decide which of the two servers to use
        if server == "cern":
            imapHost = "imap.cern.ch"
            emailAddress = "@cern.ch"
            imapUsername = "******"
        elif server == "gmail":
            imapHost = "imap.gmail.com"
            emailAddress = "@gmail.com"
            imapUsername = "******"
        else:
            self.Cout(
                'ERROR! The server argument %s is invalid. Please select between "cern" and "gmail". Exiting python shell.'
            )
            print __doc__
            sys.exit(1)

        # Prompt user to provide his login password
        self.Cout("Please provide your login password for %s to continue:" %
                  (imapUsername))
        imapPassword = getpass.getpass("\tPassword = "******"Attempting to connect to:\n\thost = %s." % (imapHost))
        connection = imaplib.IMAP4_SSL(imapHost)
        connection.login(imapUsername, imapPassword)
        self.Cout("Connecting to INBOX.")
        print connection.select("INBOX", readonly=True)  # connect to inbox.
        self.Cout(connection.welcome)

        # Search messages on server "INBOX" [search(self, charset, *criteria)] and get total number of messages in mailbox (both seen and unseen)
        AllMail = connection.search(
            None, "ALL")[1][0].split()  # returns a nice list of messages
        UnseenMail = connection.search(
            None, "UNSEEN")[1][0].split()  # returns a nice list of messages
        numAllMail = len(AllMail)
        numUnseenMail = len(UnseenMail)
        self.Cout("You have %s messages (%s NEW) in your inbox." %
                  (numAllMail, numUnseenMail))

        # Loop over all messages and write them down to files
        self.Cout('Saving NEW mail to "%s":' % (myPath))
        for mailId in UnseenMail:
            try:
                fileName = "%s.eml" % (mailId)
                newMailFiles.append(fileName)
                saveFile = open(myPath + fileName, "w")
                mailBody = connection.fetch(mailId, '(RFC822)')[1][0][1]
                saveFile.write(mailBody)
            finally:
                saveFile.close()
        self.Cout("\t%s" % ([item for item in newMailFiles]))

        # Before closing program ask user if he wants to open the new emails for the user
        openMail = self.Cin('To open NEW mail press "y"')
        if openMail == "y":
            self.Cout('Paging NEW emails. Press "q" to read the next email.')
            for mail in newMailFiles:
                myNewMail = open(myPath + mail, "r")
                pydoc.pager(
                    myNewMail.read()
                )  # similar to | less in shell. Press "q" to move to next email
        self.Cout('Done. Exiting python shell.')
        connection.logout()
Esempio n. 2
0
Usage:
./fileName.py

Permissions: 
chmod +x fileName.py

Description:
This is an example of a threaded event handler. Basically, we take a delayed thread and mix in an event loop that watched two directories for changes in filames.
So, it uses rsync -av --delete to keep 2 directories in sync if they fall out of sync, in a delayed background thread. Obviously, the delay is not strictly necessary. But,
it can have some benefits. If you add a delay (say 10 seconds), you could tell the thread to cancel if you discovered another event, such as if your master directory was 
accidentally deleted. A thread delay is a great mechanism to create conditional future operations that can still be cancelled.
'''

# Import my own modules here
import python_myFunctions as myFunctions
mf = myFunctions.CreateObject()

# All other required modules here
from threading import Timer
import sys
import time
import copy
import os
from subprocess import call


class EventLoopDelaySpawn(object):
    '''
    An Event loop class that spawns a method in delayed thread.
    '''
    def __init__(self,
Esempio n. 3
0
[attikis:python]> python python_urllib2.py -a http://cmsdoc.cern.ch/~attikis/attikis/docs/HPlusNote11_Poster.pdf -l poster.pdf
Out[1] Retrieving file in URL:
	http://cmsdoc.cern.ch/~attikis/attikis/docs/HPlusNote11_Poster.pdf
Out[2] Saved file in current directory:
	poster.pdf
Out[3] Script Execution time:
	0 days, 0 hours, 0 minutes, 1.0 seconds.
'''

import sys
import urllib
import python_myFunctions as myGFs
from optparse import OptionParser

# Object declaration here
mf = myGFs.CreateObject()
mf.StopWatchStart()
parser = OptionParser()

# Other declarations here
myURL = "http://cmsdoc.cern.ch/~attikis/attikis/docs/cv.pdf"

# Options: Mandatory
parser.add_option("-a",
                  "--url_address",
                  dest="url_address",
                  help="URL ADDRESS",
                  metavar="URL ADDRESS")
parser.add_option("-l",
                  "--local_file_name",
                  dest="local_file_name",