Beispiel #1
0
def check_email():
    """ Checks gmail for unread emails, extracts artist/song name, marks email as read, and returns artist
    and song name"""

    client = Gmail()
    USERNAME = '******'
    PASSWORD = '******'
    client.login(USERNAME, PASSWORD)

    if client.inbox().mail(unread=True):

        unread = client.inbox().mail(unread=True)

        unread[0].fetch()
        print "The input string is {}".format(unread[0].body)
        print ""
        # FORMAT MUST BE (ARTIST, SONG NAME)

        input_string = unread[0].body
        input_split = input_string.split(',')
        artist = input_split[0].lower()
        song_name = input_split[1].lower()
        test = song_name.rstrip()
        unread[0].read()

    else:
        #print "YOU HAVE READ EVERYTHING"
        artist = None
        test = None

    return artist, test
Beispiel #2
0
class GmailHandler(object):
    def __init__(self):
        """Initialise Gmail object"""
        self.obj = Gmail()
        self.obj.login(GMAIL_CONFIG['username'], GMAIL_CONFIG['password'])
        self.unread = self.obj.inbox().mail(unread=True)

    def get_unread(self, recent=False):
        if recent:
            self.unread = self.obj.inbox().mail(unread=True, on=date.today())
        else:
            self.unread = self.obj.inbox().mail(unread=True)
        return self._format_msg_count(len(self.unread))

    def search_unread(self, term):
        """Search sender or subject for a given term.

        Args:
            term (str): term to search.

        Returns:
            subject (str): subject of email with term/from sender

        """
        self.unread = self.obj.inbox().mail(unread=True)
        term = term.lower()
        result = []
        for mail in self.unread:
            mail.fetch()
            subject = mail.subject
            sender = mail.fr
            if term in subject.lower() or term in sender:
                result.append(mail.subject)

        return self._format_search_results(result)

    """Formatting methods."""

    def _format_msg_count(self, msg_count):
        if msg_count:
            msg = 'You have {msg_count} new emails.'
            msg = msg.format(msg_count=msg_count)
        else:
            msg = 'You have no new emails.'
        return msg

    def _format_search_results(self, results):
        msg = self._format_msg_count(len(results))
        results.insert(0, msg)
        msg = '\n'.join(results)
        return msg

    def __del__(self):
        """Destructor"""
        self.obj.logout()
Beispiel #3
0
class Mail():
    def __init__(self):
        # user info
        self.username = None
        self.password = None
        
        # object using the gmail library
        self.g = Gmail()
    
    
    def login(self):
        # get user info    
        username = raw_input('Username: '******'Password: '******'Unable to login'
  
  
    def logout(self):
        # logout
        self.g.logout()
                  
       
    def getNumUnread(self):
        # get number of unread email  
        try:
            return len(self.g.inbox().mail(unread=True))
        except Exception as err:
            print str(err)
Beispiel #4
0
def fetch_codes():
    client = Gmail()
    client.login(sys.argv[1], email_password)
    mails = client.inbox().mail(unread=True, sender="*****@*****.**")

    for entry in mails:
        entry.fetch()

        if 'need to complete the process:' not in entry.body:
            continue

        entry.read()
        
        # First, find the username this went too
        username = re.findall("Dear (.*),", entry.body)[0]

        # Label this as a proper steam-guard code
        entry.add_label("Codes")

        # Grab the actual steam-guard code
        _, data = entry.body.split("need to complete the process:")
        code = data.strip().split("\n", 1)[0].strip()

        store_code(entry.to, username, code)

    client.logout()
Beispiel #5
0
    def get(self, request, limit=10):
        """
        Log in to gmail using credentials from our config file and retrieve
        email to store into our db
        """
        profile = request.user.get_profile()
        username = profile.gmail_username
        password = profile.gmail_password
        source = profile.gmail_source

        g = Gmail()
        g.login(username, password)
        msgs = g.inbox().mail(sender=source)

        imported = 0
        for msg in msgs[:int(limit)]:
            try:
                email_summary = EmailSummary.objects.get(
                    message_id=msg.message_id)
                continue
            except EmailSummary.DoesNotExist:
                pass
            msg.fetch()
            email_summary = EmailSummary.objects.create(
                user=request.user,
                message_id=msg.message_id,
                subject=msg.subject, date=msg.sent_at, source_addr=source,
                imported_to_wordpress=False
            )
            email_summary.save()
            imported += 1

        return Response({"response": "imported %s messages" % imported})
Beispiel #6
0
class Mail():
    def __init__(self):
        # user info
        self.username = None
        self.password = None

        # object using the gmail library
        self.g = Gmail()

    def login(self):
        # get user info
        username = raw_input('Username: '******'Password: '******'Unable to login'

    def logout(self):
        # logout
        self.g.logout()

    def getNumUnread(self):
        # get number of unread email
        try:
            return len(self.g.inbox().mail(unread=True))
        except Exception as err:
            print str(err)
Beispiel #7
0
def run():
    g = Gmail()
    # Store your Username/Pwd in secret.py, and don't include secret.py in your github
    success = login_to_gmail(g)
    if not success:
        return  # TODO: Add error handling
    # Return list of gmail message objects
    to_me = g.inbox().mail()
    received = parse_emails(to_me, store={})
    return received
Beispiel #8
0
class YoutubeCheck:
    def __init__(self, users, passes):
        print "Started youtube checker....",
        self.gmail = Gmail()
        self.user = users
        self.password = passes
        self.emails = []
        self.lastNum = None
        self.arguments = None
        print "Done"

        self.set_args(sender="*****@*****.**", unread=True)

    @staticmethod
    def delete_email(emaillist):
        for email in emaillist:
            email.delete()

    def set_args(self, **kwargs):
        print "Attempting to start gmail (args)...",
        self.arguments = kwargs
        print "Done"

    def get_emails(self):
        return self.gmail.inbox().mail(self.arguments)

    def check_videos(self):
        self.login()
        sleep(1)
        print "Trying to check if new emails have been sent...",
        self.emails = []
        emailss = (self.get_emails())
        if len(emailss) == 0:
            return [0]
        print "Done"
        for email in emailss:
            subject = email.subject
            if '"' in subject:
                if '"' in subject[subject.index("\"") + 1:]:
                    print "Found copyrighted video...",
                    videoname = str(subject[subject.index("\"") +
                                            1:][:subject.index("\"")]).replace(
                                                "\"", "")
                    self.emails.append(videoname)
                    print "Done"
        self.delete_email(emailss)
        return self.emails

    def login(self):
        self.gmail.login(self.user, self.password)

    def logout(self):
        self.gmail.logout()
class YoutubeCheck:
    def __init__(self, users, passes):
        print "Started youtube checker....",
        self.gmail = Gmail()
        self.user = users
        self.password = passes
        self.emails = []
        self.lastNum = None
        self.arguments = None
        print "Done"

        self.set_args(sender="*****@*****.**", unread=True)

    @staticmethod
    def delete_email(emaillist):
        for email in emaillist:
            email.delete()

    def set_args(self, **kwargs):
        print "Attempting to start gmail (args)...",
        self.arguments = kwargs
        print "Done"

    def get_emails(self):
        return self.gmail.inbox().mail(self.arguments)

    def check_videos(self):
        self.login()
        sleep(1)
        print "Trying to check if new emails have been sent...",
        self.emails = []
        emailss = (self.get_emails())
        if len(emailss) == 0:
            return [0]
        print "Done"
        for email in emailss:
            subject = email.subject
            if '"' in subject:
                if '"' in subject[subject.index("\"")+1:]:
                    print "Found copyrighted video...",
                    videoname = str(subject[subject.index("\"")+1:][:subject.index("\"")]).replace("\"", "")
                    self.emails.append(videoname)
                    print "Done"
        self.delete_email(emailss)
        return self.emails

    def login(self):
        self.gmail.login(self.user, self.password)

    def logout(self):
        self.gmail.logout()
def acceptEmailTerms(listing):
    gmail = Gmail()
    gmail.login(gmailUser,gmailPass)
    today = date.today()
    year = today.year
    month = today.month
    day = today.day
    
    print("Receiving email confirmation...")
    time.sleep(60)
    print ("Checking email")
    emails = gmail.inbox().mail(sender="*****@*****.**",unread=True,after=datetime.date(year, month, day-1))
    termsUrl = getCraigslistEmailUrl(listing,emails)
    acceptTermsAndConditions(listing,termsUrl)

    gmail.logout()
    print ("Confirmed")
def acceptEmailTerms(listing):
    gmail = Gmail()
    gmail.login(gmailUser,gmailPass)

    today = date.today()
    year = today.year
    month = today.month
    day = today.day

    time.sleep(120)
    print "Checking email"
    emails = gmail.inbox().mail(sender="*****@*****.**",unread=True,after=datetime.date(year, month, day-1))
    termsUrl = getFirstCraigslistEmailUrl(listing,emails)
    acceptTermsAndConditions(listing,termsUrl)

    gmail.logout()
    print "Done Checking Email"
Beispiel #12
0
def _get_an_email(gmail_configs, index):
    """
    Log in to gmail using credentials from our config file and retrieve
    an email from our sender with a given index-number.
    """
    g = Gmail()
    g.login(gmail_configs['username'], gmail_configs['password'])
    msg = g.inbox().mail(sender=gmail_configs['source_address'])[index]
    msg.fetch()
    raw_message = msg.message
    html_body = ''
    if raw_message.get_content_maintype() == "multipart":
        for content in raw_message.walk():
            print content.get_content_type()
            if content.get_content_type() == "text/html":
                html_body = content.get_payload(decode=True)
    return html_body
    def monitorEmail(self):
        if not self.isSafetySwitchOff():
            self.sendMonitorErrorEmail("Monitor Email still broken: safety switch turned on")
            return

        g = Gmail()
        g.login(SECRETS_DICT['EMAIL_USERNAME'], SECRETS_DICT['EMAIL_PASSWORD'])
        # play with your gmail...
        messages = g.inbox().mail(unread=True, sender="*****@*****.**")
        for x in messages:
            x.fetch()
            try:
                self.handleEmail(x)
            except Exception as e:
                x.add_label("Monitor Email Job Error")

        g.logout()
    def monitorEmail(self):
        if not self.isSafetySwitchOff():
            self.sendMonitorErrorEmail(
                "Monitor Email still broken: safety switch turned on")
            return

        g = Gmail()
        g.login(SECRETS_DICT['EMAIL_USERNAME'], SECRETS_DICT['EMAIL_PASSWORD'])
        # play with your gmail...
        messages = g.inbox().mail(unread=True,
                                  sender="*****@*****.**")
        for x in messages:
            x.fetch()
            try:
                self.handleEmail(x)
            except Exception as e:
                x.add_label("Monitor Email Job Error")

        g.logout()
class UtIntfGmail(object):
    def __init__(self, dictCreds):
        self.init(dictCreds)
        pass
    
    def init(self, dictCreds):
        self.__api_Gmail = Gmail()
        self.__api_Gmail.login(dictCreds['username'], dictCreds['password'])
        pass
    
    def getEmails(self, user):
        bRet = True
        bodyList = []
        mailList = self.__api_Gmail.inbox().mail(unread=True, sender=user)
        for m in mailList:
            m.fetch()
            bodyList.append(m.body)
        
        return bRet, bodyList
Beispiel #16
0
def acceptEmailTerms(listing):
    gmail = Gmail()
    gmail.login(gmailUser, gmailPass)

    today = date.today()
    year = today.year
    month = today.month
    day = today.day

    time.sleep(120)
    print "Checking email"
    emails = gmail.inbox().mail(sender="*****@*****.**",
                                unread=True,
                                after=datetime.date(year, month, day - 1))
    termsUrl = getFirstCraigslistEmailUrl(listing, emails)
    acceptTermsAndConditions(listing, termsUrl)

    gmail.logout()
    print "Done Checking Email"
class ProxyZipDownloader:

    def __init__(self, username, password, abs_path_zips):
        self.username = username
        self.password = password
        self.abs_path_zips = abs_path_zips
        self.g = Gmail()
        self.g.login(username, password)
    
    def __remove_all_zips__(self):
        for file_name in os.listdir(self.abs_path_zips):
            if file_name.endswith(".zip"):
                file_to_remove = self.abs_path_zips + file_name
                print "Removing %s" % file_to_remove
                os.remove(file_to_remove)


    def __is_zip_file_old__(self, file_name):
        # proxylist-10-26-13.zip
        date_zip_file = datetime.datetime.strptime(file_name, \
                                                           'proxylist-%m-%d-%y.zip')
        date_today = datetime.datetime.now()
        return (date_today - date_zip_file).days >= 2

    def fetch_files(self):
        self.__remove_all_zips__()
        for email in self.g.inbox().mail(sender="*****@*****.**", after=datetime.datetime.now() - datetime.timedelta(days=3)):
            message = email.fetch()

            m1 = message.get_payload()[0]
            m2 = message.get_payload()[1]

            zip_file_name = m2.get_filename()
            if self.__is_zip_file_old__(zip_file_name):
                continue

            zip_file_contents = m2.get_payload(decode=True)
                    
            print "Saving %s" % zip_file_name
            f = open(self.abs_path_zips + zip_file_name, 'w')
            f.write(zip_file_contents)
            f.close()
Beispiel #18
0
    def __init__(self, **kwargs):
        super(Gmail_checker, self).__init__(**kwargs)

        # check if parameters have been provided
        username = kwargs.get('username', None)
        password = kwargs.get('password', None)

        if username is None:
            raise MissingParameterException("Username parameter required")

        if password is None:
            raise MissingParameterException("Password parameter required")

        # prepare a returned dict
        returned_dict = dict()

        g = Gmail()
        g.login(username, password)

        # check if login succeed
        logging.debug("Gmail loggin ok: %s" % g.logged_in)  # Should be True, AuthenticationError if login fails

        # get unread mail
        unread = g.inbox().mail(unread=True)

        returned_dict["unread"] = len(unread)

        if len(unread) > 0:
            # add a list of subject
            subject_list = list()
            for email in unread:
                email.fetch()
                encoded_subject = email.subject
                subject = self._parse_subject(encoded_subject)
                subject_list.append(subject)

            returned_dict["subjects"] = subject_list

        logger.debug("gmail neuron returned dict: %s" % str(returned_dict))
        # logout of gmail
        g.logout()
        self.say(returned_dict)
Beispiel #19
0
def in_(destdir, instream):
    input = json.load(instream)

    username = input['source']['username']
    password = input['source']['password']
    version = input.get('version')
    uid = version.get('uid', "") if version is not None else ""

    common.msg("logging into gmail as '{0}'".format(username))
    g = Gmail()

    # login, fail if unable to authenticate
    try:
        g.login(username, password)
    except:
        common.msg("unable to log in")
        exit(1)

    # fetch this particular email
    common.msg("fetching email with uid '{0}'".format(uid))
    msg = g.fetch_multiple_messages({uid: Message(g.inbox(), uid)})[uid]

    # if we haven't found the required email message, then exit
    if msg is None or msg.message is None:
        common.msg("unable to find email with uid '{0}'".format(uid))
        exit(1)

    # put it on a file system
    common.msg("writing email '{0}' to {1}".format(msg.subject, destdir))
    with safe_open(os.path.join(destdir, "email"), 'w') as f:
        f.write(json.dumps(toJSON(msg)))

    # log out and swallow the error
    try:
        g.logout()
    except:
        pass

    metadata = [{'name': 'uid', "value": msg.uid}, {'name': 'subject', "value": msg.subject}]
    return {'version': {'uid': msg.uid}, 'metadata': metadata}
def main():
    path = "C:\\Users\\L.SeonHo\\Desktop\\result\\"
    gmaps = list()  # for location
    gmap_path = str()   # for full path
    g = Gmail()
    g.login('bob5leesh', 'rlayuna#0905')
    if not os.path.isdir(path):
        os.mkdir(path)
    set_sqlite(path)

    for i in range(16, 30):
        mailday = date(2016, 7, i)
        daypath =  "C:\\Users\\L.SeonHo\\Desktop\\result\\" + str(mailday) +"\\"    # for create day folder
        daygmap = list()    # create day gmap
        if not os.path.isdir(daypath):
            os.mkdir(daypath)   # create folder
        emails = g.inbox().mail(on = mailday, sender = '*****@*****.**')

        for email in emails:
            flock = fl0ckfl0ck(email) # one mail routine
            flock.path = daypath
            flock.GetGmail()
            gmap_path = flock.path
            if flock.ShortToFull() != 0: # in : success get full url / out : fail get full url
                flock.GetImage()
                flock.GetHash()
                flock.GetGPS()
                # check exist gps info from file
                if str(flock.gps_lat) == 'None' or str(flock.gps_lon) == 'None':
                    pass
                elif str(flock.gps_lat) == 'N/A' or str(flock.gps_lon) == 'N/A':
                    pass
                else:
                    gmaps.append(flock.MakeGmap())       # setting day gmap
                    daygmap.append(flock.MakeGmap())     # setting full gmap
            flock.OutCSV()  # create CSV file
            flock.OutSQLite(path)   # create SQLite database
        if len(daygmap) != 0:
            get_googlemap(daygmap, gmap_path)   # get day gmap
        get_googlemap(gmaps, path)  # get full gmap
Beispiel #21
0
def findPayments(username, password):
    
    # Main Part, use Gmail to find venmo balances
    file = open('recent.txt', 'r')
    most_recent = file.read()
    file.close()
    IDs = [0,most_recent]
    charges = {}

    #can use this if we only want to check most recent emails
    #then = datetime.datetime.now().replace(hour=8, minute=0, second=0, microsecond=0)

    '''


    Make benefits_on true to provide benefits to DKEggertor founders


    '''
    benefits_on = False
    g = Gmail()
    g.login(username, password)
    newMail = g.inbox().mail(fr="*****@*****.**")
    print "got mail"
    #Filter venmo emails that are payments emails from venmo
    payments = filterPayments(newMail)
    print "filtered"
    #Can use this part to implement only most recent email checking, Note: use email.sent_at to get the emails timestamp.
    #for i in pay:
        #if i.sent_at >= then:
            #payments.append(i)

    #Iterate through payment emails to find balances
    i = 0
    while i < len(payments):
        #Check if the ID number of the email has already been checked
        #as this prevents checking emails twice and incorrectly calculating balances
        if payments[i].uid not in IDs:
            print "Test 1"
            #Check if email is a payment to DKE Keg 
            if isKegEmail(payments[i]) and int(payments[i].uid) >= int(most_recent)+1:
                print "Test 2"
                #Seperate out the subject of the email to find Name and Amount that was paid 
                IDs.append(payments[i].uid) 
                payments[i].fetch()
                print "Fetched"
                message =  payments[i].subject
                print "subject"
                name = message.split(" p")[0]
                if len(message.split("$")[1]) >= 10:
                    amount = float(message.split("$")[1].split(" ")[0])
                else:
                    amount = float(message.split("$")[1])

                #Update amount if name is already in the database
                if name in charges:
                    amount = charges[name] + amount

                #This check is only for when I (Mike DeLaus) pay from the my venmo account as it is the same email we use for DKE Keg
                if name != "You":
                    charges[name] = amount

                #Provides benefits for the founding members of DKEggerator
                founders = ["Michael DeLaus", "Ryan Kelly", "Mitch Maisel"]
                for name in founders:
                    if benefits_on == True:
                        charges[name] = 999999999999
                file = open('recent.txt', 'w')
                most_recent = payments[i].uid
                file.write(str(most_recent))
                file.close()
        i+=1
    return charges

    #Sleep the program so we don't constantly check, can probably find better way to do this
    #time.sleep(60)

    #Logout of email so next check uses a refreshed inbox
    g.logout()
Beispiel #22
0
        self.to_dict = {
            'attachments': gm.attachments,
            'body': gm.body,
            'to': gm.to,
            'cc': gm.cc,
            'flags': gm.flags,
            'headers': gm.headers,
            'message_id': gm.message_id,
            'sent_at': str(gm.sent_at),
            'subject': gm.subject,
            'thread': gm.thread,
            'thread_id': gm.thread_id
        }


if __name__ == '__main__':

    g = Gmail()
    g.login("grfvanfvphermmn", "pbzchgrefrphevgl")
    emails = g.inbox().mail()
    mailist = []
    for e in emails[:10]:
        e.fetch()
        m = Mailwrapper(e)
        mailist.append(json.dumps(m.to_dict))
        # print e.body

    with open('data.json', 'w') as fp:
        json.dump(mailist, fp)
    g.logout()
Beispiel #23
0
def calculate_email_stats(
    USERNAME,
    ACCESS_TOKEN,
    DAYS,
    ALIASES=[],
    IGNORE_EMAILS=[],
    IGNORE_SUBJECT_KEYWORDS=[],
    IGNORE_BODY_KEYWORDS=[],
    MIN_THREAD_LENGTH=0,
    ):
    """
    Calculate a bunch of stats and return a dict of values for rendering.
    """

    ALIASES.append(USERNAME)
    # Log in to Gmail
    g = Gmail()
    g.authenticate(USERNAME, ACCESS_TOKEN)

    write( "Login success!")

    # Pull all emails
    now = datetime.datetime.now()
    after = now - datetime.timedelta(days=DAYS)
    emails = g.all_mail().mail(
                prefetch=True,
                after = after,
             )
    total_email_count = len(emails)
    write("Retrieved %s emails." % total_email_count)

    # Clean emails
    could_not_fetch = [email for email in emails if not email.body]
    emails = [email for email in emails if email.body]

    no_thread_id = [email for email in emails if not email.thread_id]
    emails = [email for email in emails if email.thread_id]

    ignored_for_email = [email for email in emails if \
                             (email_in_aliases(email.fr, IGNORE_EMAILS) or \
                              email_in_aliases(email.to, IGNORE_EMAILS))]
    emails            = [email for email in emails if \
                         not (email_in_aliases(email.fr, IGNORE_EMAILS) or \
                              email_in_aliases(email.to, IGNORE_EMAILS))]

    ignored_for_subject = [email for email in emails if \
                           email_in_aliases(
                               email.subject,
                               IGNORE_SUBJECT_KEYWORDS)]
    emails              = [email for email in emails if \
                           not email_in_aliases(
                               email.subject,
                               IGNORE_SUBJECT_KEYWORDS)]

    ignored_for_body    = [email for email in emails if \
                           email_in_aliases(
                               email.body,
                               IGNORE_BODY_KEYWORDS)]
    emails              = [email for email in emails if \
                           not email_in_aliases(
                               email.body,
                               IGNORE_BODY_KEYWORDS)]

    write("Finished grabbing emails")

    # Group emails by thread
    threads = {}

    for email in emails:
        if not email.thread_id in threads.keys():
            threads[email.thread_id] = []
        threads[email.thread_id].append(email)

    write("Removed bad emails")

    # Sort and pull off the last responder
    last_responder_was_me = []
    last_responder_was_counterparty = []
    selfies = []
    only_sender_was_me = []

    for key in threads.keys():
        thread = threads[key]
        #if len(thread) > 5:
        #    import ipdb;
        #    ipdb.set_trace()
        thread.sort(cmp=lambda x,y:cmp(x.sent_at, y.sent_at), reverse=True)
        conversation = Conversation(thread)
        last_email = conversation.last_email

        # import ipdb
        # if "rentapp" in last_email.fr and "rentapp" in last_email.to:
        #     ipdb.set_trace()
        # I wrote it to someone other than me
        if (email_in_aliases(last_email.fr, ALIASES) and \
            not email_in_aliases(last_email.to, ALIASES)):
            last_responder_was_me.append(conversation)
        # I wrote it to myself
        elif (email_in_aliases(last_email.fr, ALIASES) and \
              email_in_aliases(last_email.to, ALIASES)):
            selfies.append(conversation)
        # Someone else wrote it
        else:
            last_responder_was_counterparty.append(conversation)

        if all([email_in_aliases(email.fr, ALIASES) for email in conversation.thread]):
            only_sender_was_me.append(conversation)

    inbound_emails = [email for email in emails \
                          if (email_in_aliases(email.to, ALIASES) and \
                          not email_in_aliases(email.fr, ALIASES))]
    outbound_emails = [email for email in emails \
                          if (email_in_aliases(email.fr, ALIASES) and \
                          not email_in_aliases(email.to, ALIASES))]
    selfie_emails = [email for email in emails \
                          if (email_in_aliases(email.fr, ALIASES) and \
                          email_in_aliases(email.to, ALIASES))]
    other_emails = [email for email in emails \
                          if (not email_in_aliases(email.fr, ALIASES) and \
                          not email_in_aliases(email.to, ALIASES))]

    email_days = set(email.sent_at.date() for email in emails)
    emails_received_by_day = [(email_day, len([email for email in inbound_emails if email.sent_at.date() == email_day])) for email_day in email_days]
    emails_sent_by_day = [(email_day, len([email for email in outbound_emails if email.sent_at.date() == email_day])) for email_day in email_days]

    emails_received_by_day.sort(cmp=lambda x,y: cmp(x,y))
    emails_sent_by_day.sort(cmp=lambda x,y: cmp(x,y))

    emails_received_by_day = [{"date": "{} {}".format(day_of_week(date.weekday()), date.day), "count": count} for (date, count) in emails_received_by_day]
    emails_sent_by_day = [{"date": "{} {}".format(day_of_week(date.weekday()), date.day), "count": count} for (date, count) in emails_sent_by_day]

    write("Sorted emails")

    write("* " * 25)

    inbox_total = g.inbox().count()
    inbox_unread = g.inbox().count(unread=True)
    total_email_count = total_email_count
    ignored_for_email = ignored_for_email
    ignored_for_subject = ignored_for_subject
    ignored_for_body = ignored_for_body

    num_remaining_emails = len(emails)
    num_threads = len(threads)
    num_inbound_emails = len(inbound_emails)
    num_outbound_emails = len(outbound_emails)
    num_selfie_emails =  len(selfie_emails)
    num_other_emails = len(other_emails)

    num_last_responder_was_me = len(last_responder_was_me)
    num_last_responder_was_counterparty =  len(last_responder_was_counterparty)

    response_times = []
    for thread in (last_responder_was_counterparty + last_responder_was_me):
        response_times.extend(thread.get_response_times())

    senders = {}
    for response_time in response_times:
        if not response_time.get("fr"):
            continue
        sender = response_time.get("fr").lower()
        name, email_address = parseaddr(sender)
        if not email_address in senders.keys():
            senders[email_address] = {'response_times':[]}
        senders[email_address]['response_times'].append(response_time.get("response_time"))

    emails_sent_per_person = [(sender, len(senders[sender].get("response_times"))) for sender in senders.keys()]
    emails_sent_per_person.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)

    for sender in senders.keys():
        senders[sender]['num_no_response'] = len([response_time is None for response_time in senders[sender]['response_times']])
        senders[sender]['response_times'] = [response_time for response_time in senders[sender]['response_times'] if not response_time is None]

    my_response_times = []
    for sender in senders.keys():
        if email_in_aliases(sender, ALIASES):
            my_response_times.extend(senders[sender].get("response_times"))
    my_response_times = [int(t/3600) for t in my_response_times]


    last_responder_was_me = [convert_conversation_object_to_dict(i) for i in last_responder_was_me]
    last_responder_was_counterparty = [convert_conversation_object_to_dict(i) for i in last_responder_was_counterparty]
    only_sender_was_me = [convert_conversation_object_to_dict(i) for i in only_sender_was_me]
    only_sender_was_me.sort(cmp=lambda x,y: cmp(x.get("length"), y.get("length")), reverse=True)
    emails_sent_per_person.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)

    ignored_for_email = [convert_email_object_to_dict(i) for i in ignored_for_email]
    ignored_for_subject = [convert_email_object_to_dict(i) for i in ignored_for_subject]
    ignored_for_body = [convert_email_object_to_dict(i) for i in ignored_for_body]

    #_last_responder_was_me = []
    #for conversation in last_responder_was_me:
    #    _last_responder_was_me.append(
    #        dict(thread_length=conversation.length,
    #             to=conversation.last_email.to,
    #             url=conversation.get_gmail_url(),
    #             subject=conversation.last_email.subject))
    #last_responder_was_me = _last_responder_was_me
    
    #_last_responder_was_counterparty = []
    #for conversation in last_responder_was_counterparty:
    #    if conversation.length > MIN_THREAD_LENGTH:
    #        _last_responder_was_counterparty.append(
    #            dict(
    #                thread_length=conversation.length,
    #                fr=conversation.last_email.fr,
    #                 url=conversation.get_gmail_url(),
    #                subject=conversation.last_email.subject))
    #last_responder_was_counterparty = _last_responder_was_counterparty

    keys = [
        "inbox_total",
        "inbox_unread",
        "total_email_count",
        "ignored_for_email",
        "ignored_for_subject",
        "ignored_for_body",
        "num_remaining_emails",
        "num_threads",
        "num_inbound_emails",
        "num_outbound_emails",
        "num_selfie_emails",
        "num_other_emails",
        "num_last_responder_was_me",
        "num_last_responder_was_counterparty",
        "last_responder_was_me",
        "last_responder_was_counterparty",
        "only_sender_was_me",
        "senders",
        "response_times",
        "my_response_times",
        "emails_sent_per_person",
        "DAYS",
        "emails_sent_by_day",
        "emails_received_by_day",
        ]
    return dict([(key, locals()[key]) for key in keys])
def readMail(): # Read & Parse the mail
    index = 0
    gpsflag = 0

    seplat = 0.0
    maxlat = 0.0
    minlat = 999.999
    datalat = []


    seplon = 0.0
    maxlon = 0.0
    minlon = 999.999
    datalon = []
    gpsdata = ""
    try:       
        flat = "N/A"
        flon = "N/A"
        g = Gmail()
        g = gmail.login('*****@*****.**', 'qaz123ws')
        print "[*] Authentication complete."
        emails = g.inbox().mail(sender='*****@*****.**')
        
        print "[*] Engaging email parsing."
        for email in emails:
            index = index + 1
            email.read()
            email.fetch()
            time = email.sent_at
            print time
            time = time + datetime.timedelta(hours=9)
            print time
            body = email.body
            print "[*] RAW body : "+body
            if (len(body) >= 12) and (body.find("http") == -1) :
                body = b64(email.body)
                print "[*] Base64 decoded body : "+body
            surl = re.findall('(https?:\/\/\S+)', str(body))
            surl = str(surl)[2:-2]
            path = (surl.split("/")[-1])
            surl = surl.replace(path, '')
            path = re.sub('[=@#?$}.]', '', path.decode('utf-8'))
            surl = surl + path
            if len(str(surl).split("/")[-1]) > 4 and str(surl).find("grep.kr") != -1 :
               print str(surl.find("grep.kr"))
               path = (surl.split("/")[-1])
               surl = surl.replace(path, '')
               path = path[:4]
               surl = surl + path
               print "[*] grep.kr processed: ", surl
            if str(surl).decode('utf-8').find(str("\\x")) > -1 :
                print surl
                print str(surl).decode('utf-8')
                surl = re.sub('(\\\\x..)', '', str(surl).decode('utf-8'))                
                print "[*] Junk data removed: ", surl
            if str(surl).find('\\n') != -1:
                surl = str(surl)[:-2]
                print "[*] New line removed: ", surl
            furl, surl = unshortURL(surl.decode('utf-8'))            
            print "[*] URL Unshortened"
            print "[*] Shortened URL : "+surl
            print "[*] Full URL : "+str(urllib.unquote(urllib.unquote(furl)).decode('utf-8').encode('cp949'))
            filename = furl.split('/')[-1]
            filepath = (dirpath+"\\"+filename)
            filepath =  urllib2.unquote(urllib.unquote(filepath)).decode('utf-8').encode('cp949')
            req = urllib2.Request(furl, headers={ 'User-Agent': 'Mozilla/5.0' })
            req.add_header('Accept', 'application/json')
            file = urllib2.urlopen(req)
            file.close()
            urllib.urlretrieve(furl, filepath)
            
            fMD5 = MD5(filepath)
            fSHA1 = SHA1(filepath)
            if filepath.split('.')[-1] == 'jpg' :                         
                flat, flon = jpgGPS(filepath)
                if flat!="N/A" and flon!="N/A" :
                    print "[*] GPS data found, Lat: " + str(flat) +" Lon:"+str(flon)
                    flat = float(flat)
                    flon = float(flon)
                    datalat.append(flat)
                    datalon.append(flon)               
                    if(flat > maxlat) :
                        maxlat = flat
                    if(flat < minlat) :
                        minlat = flat
                    if(flon > maxlon) :
                        maxlon = flon
                    if(flon < minlon) :
                        minlon = flon                   
                    gpsflag=1
                    
            
            furl = urllib.unquote(urllib.unquote(furl))
            filename = urllib.unquote(urllib.unquote(filename))
            print "[*] Information added to CSV file"
            addCsv(filepath, str(index), str(time), str(surl), str(furl), str(filename), str(flat), str(flon), str(fMD5), str(fSHA1))
            SQLDump(str(time), str(surl), str(furl), str(filename), str(flat), str(flon), str(fMD5), str(fSHA1))      
        finallat = datalat[:]      
        finallon = datalon[:]
    except gmail.AuthenticationError:
        print "Auth fail"
    print "[*] Mail read complete."
    if gpsflag == 1:
        latsum = 0.0
        lonsum = 0.0
        for i in datalat:
            latsum = latsum + i
        latavg = latsum / len(datalat)
        for i in datalon:
            lonsum = lonsum + i
        lonavg = lonsum / len(datalon)
        if((abs(maxlat-minlat) > 1.5) or abs(maxlon-minlon) > 1.5) and ((abs(latavg-minlat) > 1.5) or (abs(lonavg-minlon) > 1.5)) :
            datalat.remove(maxlat)
            datalat.remove(minlat)
            datalon.remove(maxlon)
            datalon.remove(minlon)
            sum = 0.0
            latsum = 0.0
            lonsum = 0.0
            print maxlat, minlat, latavg, datalat, finallat 
            print maxlon, minlon, lonavg, datalon, finallon
            
            print lonavg
            if(abs(latavg-minlat) > 1.5):
                print "[*] latavg - minlat : ",latavg-minlat
                finallat.remove(minlat)
                seplat = minlat
            elif(abs(maxlat-latavg) > 1.5) :
                print "[*] maxlat - latavg : ", maxlat-latavg
                finallat.remove(maxlat)
                seplat = maxlat
            if(abs(maxlon-lonavg) > 1.5) :
                print "[*] maxlon - lonavg : ", maxlon-lonavg
                finallon.remove(maxlon)
                seplon = maxlon
            elif(abs(lonavg-minlon) > 1.5):
                print "[*] lonavg - minlon : ",lonavg-minlon
                finallon.remove(minlon)
                seplon = minlon
            
            seperateGPSMAP(filepath, seplat, seplon)
            print seplat, seplon
        for i in range(len(finallat)):
            gpsdata = gpsdata+str(finallat[i])+","+str(finallon[i])+"|"
        GPSMAP(filepath, gpsdata)
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_SSLv23)))
urllib2.install_opener(opener)
today=str(datetime.datetime.now())[:10] # YYYY MM DD for name of directory
year = today[:4]
month = today[5:7]
day = today[-2:]
dirpath = os.path.expanduser('~') + '\Desktop\\result\\' + today # Path of directory
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
flat = "N/A"
flon = "N/A"
g = Gmail()
g = gmail.login('*****@*****.**', 'qaz123ws')
print "[*] Authentication complete."
emails = g.inbox().mail(sender='*****@*****.**')
        
print "[*] Engaging email parsing."
for email in emails:
        email.read()
        email.fetch()
        time = email.sent_at
        print email.subject
        print "original time: ",time
        time = time + datetime.timedelta(hours=9)
        print "processed time: ",time
        print "________________\r\n"
todayDir()
SQLInit()
makeCsv()
readMail()
Beispiel #26
0
import serial
import time
from datetime import datetime
from gmail import Gmail

# Don't forget to replace the email and password in config.py!
g = Gmail()
g.login(config.email, config.password)

# Runs every 10 seconds
while True:
    # Connect to the Bean via virtual serial port. Wait 250ms at most.
    # Set up the Bean you want to use as a virtual serial device in the
    # Bean Loader App for OS X.
    ser = serial.Serial('/tmp/tty.LightBlue-Bean', 9600, timeout=0.25)
    twitter_emails = g.inbox().mail(sender='*****@*****.**')
    facebook_emails = g.inbox().mail(sender='facebookmail.com')
    all_emails = g.inbox().mail(unread=True)

    # Display how many emails were found in the inbox
    print datetime.now()
    print 'Twitter notifications:', len(twitter_emails)
    print 'Facebook notifications:', len(facebook_emails)
    print 'All unread emails:', len(all_emails)
    print

    # Mark all emails as read so we don't trigger on the same email each time
    for email in twitter_emails:
        email.read()
    for email in facebook_emails:
        email.read()
def check(instream):
    input = json.load(instream)

    username = input['source']['username']
    password = input['source']['password']
    version = input.get('version')
    startUid = version.get('uid', "") if version is not None else ""

    common.msg("logging into gmail as '{0}'".format(username))
    g = Gmail()

    # login, fail if unable to authenticate
    try:
        g.login(username, password)
    except:
        common.msg("unable to log in")
        exit(1)

    # see what emails have appeared
    messages = g.inbox().mail(unread=True, prefetch=True)
    messages = sorted(messages, key=lambda m: m.sent_at)

    messages_after_start = []
    found = False
    for m in messages:
        # only consider emails after the given startUid
        if startUid == m.uid:
            found = True

        common.msg("[{0}] {1} [check = {2}]".format(m.uid, m.subject, found))
        if found:
            messages_after_start.append(m)

    # if it's the very first call, let's return the very first email
    if len(startUid) <= 0:
        messages_after_start = [messages[0]] if len(messages) > 0 else []
    else:
        # if nothing has been found, let's return the complete list
        if not found:
            messages_after_start = messages

    # return the resulting list
    result = []
    for m in messages_after_start:
        try:
            # read the corresponding email message (so we don't receive it during the next check)
            # but keep it in the mailbox and don't move anywhere, so it doesn't change uid
            m.read()
            result.append({'uid': m.uid})
        except:
            common.msg("[{0}] {1} [unable to mark message as read".format(
                m.uid, m.subject))
            break

    # log out and swallow the error
    try:
        g.logout()
    except:
        pass

    return result
# import getemailcontent.py
import sys
sys.path.append('D:/python_stufff/algorithm')
import gmail
from gmail import Gmail
import datetime
import xlwt 	#excel python library
import xlrd    #write excel
import re      #regular expression
import types 
import numpy as np
g = Gmail()
username='******'
password='******'
g.login(username, password)
g.inbox().mail(unread=True, sender="*****@*****.**")#sender
data=g.inbox().mail(on=datetime.date(2014, 3, 26))       #date
#print len(data) #number of emails

for i in range(len(data)-1):
    data[i].fetch() #get email
   # print data[i].body #testing and printing email

#-----------------------------------------------------------------------------------------------------------------------#
#each email including contents like attachement is not attached, find all attachments than erase everything before that
maillist=(len(data)-1,2)
indexlist=np.zeros(maillist)

for i in range(5):
    indexlist[i,:]=np.asarray(re.search('Attached',data[i].body).span())
from account import Account
from gmail import Gmail


gmail = Gmail()

while True:
    choice = input('1. Sign up\n2. Login\n')
    if choice == '1':
        new_account = Account()
    elif choice == '2':
        user_account = Account.login()
        if user_account != None:
            while True:
                choice2 = input('1. Inbox\n2.Send Email\n')
                if choice2 == '1':
                    inbx = gmail.inbox(user_account)
                    print(inbx)
                    choice3 = input('Enter the index of message to view (max {}) / -1 to go back: '.format(len(inbx)-1))
                    if int(choice3) == -1:
                        pass
                    else:
                        print(gmail.view_message(int(choice3),inbx))
                elif choice2 == '2':
                    #to_email, msg, subject, user
                    t = input('To: ')
                    s = input('Subject: ')
                    m = input('Message: ')
                    gmail.send_email(t, m, s, user_account)

Beispiel #30
0
    browser_url = browser.get_url()
    for url in success_urls:
        if browser_url.startswith(url):
            return True
    return False


if __name__ == '__main__':
    dir_here = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(dir_here, 'private/funshop_result.txt')
    g = Gmail()
    while not g.logged_in:
        time.sleep(1)
        g.login(private.GMAIL_ID, private.GMAIL_PASSWORD)
    print("logged in!")
    mails = g.inbox().mail(unread=True, sender='*****@*****.**')
    print("total %d unread mails from funshop" % len(mails))

    for m in mails:
        m.fetch()
        content = m.message.get_payload(decode=True)
        url = get_delivery_point_urls(content)
        if url is None:
            print('No point button on this email')
            is_success = True
        else:
            is_success = get_delivery_point(url)
        with open(filename, 'a') as fp:
            fp.write('%s: %s\n' % (datetime.datetime.now().isoformat(), is_success))
        if is_success:
            print('success!')
Beispiel #31
0
from account import Account
from gmail import Gmail

gmail = Gmail()

while True:
    choice = input('1. Sign up\n2. Login\n')
    if choice == '1':
        new_account = Account()
    elif choice == '2':
        user_account = Account.login()
        if user_account != None:
            while True:
                choice2 = input('1. Inbox\n2.Send Email\n')
                if choice2 == '1':
                    inbx = gmail.inbox(user_account)
                    print(inbx)
                    choice3 = input(
                        'Enter the index of message to view (max {}) / -1 to go back: '
                        .format(len(inbx) - 1))
                    if int(choice3) == -1:
                        pass
                    else:
                        print(gmail.view_message(int(choice3), inbx))
                elif choice2 == '2':
                    #to_email, msg, subject, user
                    t = input('To: ')
                    s = input('Subject: ')
                    m = input('Message: ')
                    gmail.send_email(t, m, s, user_account)
import serial
import time
from datetime import datetime
from gmail import Gmail

# Don't forget to replace the email and password in config.py!
g = Gmail()
g.login(config.email, config.password)

# Runs every 10 seconds
while True:
    # Connect to the Bean via virtual serial port. Wait 250ms at most.
    # Set up the Bean you want to use as a virtual serial device in the
    # Bean Loader App for OS X.
    ser = serial.Serial('/tmp/tty.LightBlue-Bean', 9600, timeout=0.25)
    twitter_emails = g.inbox().mail(sender='*****@*****.**')
    facebook_emails = g.inbox().mail(sender='facebookmail.com')
    all_emails = g.inbox().mail(unread=True)

    # Display how many emails were found in the inbox
    print datetime.now()
    print 'Twitter notifications:', len(twitter_emails)
    print 'Facebook notifications:', len(facebook_emails)
    print 'All unread emails:', len(all_emails)
    print

    # Mark all emails as read so we don't trigger on the same email each time
    for email in twitter_emails:
        email.read()
    for email in facebook_emails:
        email.read()
Beispiel #33
0
# Settings
login = '******'  # Login for gmail account
password = '******'  # Password for gmail account
template = ['Rejected', 'Undeliverable', 'Failure',
            'Delay']  # Stop words to search bounces
safeemail = [login, '*****@*****.**'
             ]  # email that shouldn't be in the final list
# The big number of message in inbox can stuck your OS. Python eat a lot of RAM.
rd = True  # Param to get unread only messages. If you want to get all mesagges put it False
st = False  # Star message. If you want to star message put it True
dl = False  # Delete message. If you want to delete message put it True

g = Gmail()
g.login(login, password)
# there are a lot of parameters for filtering here https://github.com/charlierguo/gmail
mails = g.inbox().mail(unread=rd)  # Get emails

with open('bounced.txt', 'a') as result:
    for mail in mails:
        res = ''
        mail.fetch()
        if any(tmp in mail.subject for tmp in template):
            try:
                res = mail.headers['X-Failed-Recipients']
                print 'EMAIL:', res, '\033[32m', mail.fr, '\033[0m'
                result.write(res + '\n')
                if st:
                    mail.star()
                if dl:
                    mail.delete()
                continue
def doScrape(Con, q):
    try:
        g = Gmail()
        ################ LOGIN #####################################
        q.put(('Logging In', 5),)
        logger.info("Logging In")
        try:
            g.login(Con.Username, Con.Password)
        except AuthenticationError:
            logger.exception(sys.exc_info())
            q.put(('Login Failed', 100),)
            return "AUTH_ERROR"
        ############################################################

        ################ GET LABEL MAILBOX #########################
        mailbox = None
        q.put(('Getting Mailbox', 10),)
        logger.info("Getting Mailbox")
        try:
            if Con.Label.lower() == 'inbox':
                mailbox = g.inbox()
            else:
                mailbox = g.mailbox(Con.Label)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in fetching Gmail Label', 100),)
            return "LABEL_FETCH_ERROR"
        if not mailbox:
            q.put(('Gmail Label Not Found', 100),)
            return "LABEL_NOT_FOUND"
        ############################################################

        ################ GET EMAILS ################################
        mails = None
        q.put(('Searching For Emails', 15),)
        logger.info("Searching Emails")
        try:
            afterDate = Con.FromDate - timedelta(days=1)
            beforeDate = Con.ToDate + timedelta(days=1)
            mails = mailbox.mail(subject='Fiverr: Congrats! You have a new order',
                                 after=afterDate, before=beforeDate)
            mails.extend(mailbox.mail(subject='just ordered an Extra',
                                      after=afterDate, before=beforeDate))
            # mails = mailbox.mail(after=Con.FromDate, before=Con.ToDate)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in searching for emails', 100),)
            return "EMAILS_FETCH_ERROR"
        if len(mails) == 0:
            q.put(('No Emails Found with search criteria', 100),)
            return "NO_EMAIL_FOUND"
        ############################################################

        ################ FETCH EMAILS ##############################
        q.put(('Fetching Emails', 20),)
        logger.info("Scraping Order Data From Emails")
        Con.Orders = []
        logger.info("Num of Emails found: " + str(len(mails)))
        try:
            for mail in mails:
                msg = "Fetching Email " + str(mails.index(mail)+1) + ' of ' + str(len(mails))
                per = 20 + int((float(mails.index(mail)+1) * 100.0 * 0.6 / float(len(mails))))
                q.put((msg, per),)
                #logger.info(msg)
                mail.fetch()
                gmailEvents.extract_orders_from_email(mail, Con)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in fetching emails', 100),)
            return "EMAIL_FETCH_ERROR"
        ############################################################

        # return 'SUCCESS'

        ################ CALCULATE TOTAL AMOUNT ####################
        q.put(('Calculating Total and Revenue', 85),)
        logger.info("Calculating Total Amount")
        gmailEvents.calculate_total_amount(Con)
        ############################################################

        ################ GENERATE XLS ##############################
        q.put(('Generating XLS', 90),)
        logger.info("Generating XLS")
        gmailEvents.generate_xls(Con)
        ############################################################

        q.put(('Logging Out of Gmail', 95),)
        g.logout()
        q.put(('SUCCESS', 100),)
        return 'SUCCESS'
    except:
        if g:
            g.logout()
        logger.exception(sys.exc_info())
        q.put(('Error Occurred', 100),)
        return "ERROR"
Beispiel #35
0
    year = int(date_str.split("-")[0])
    month = int(date_str.split("-")[1])
    day = int(date_str.split("-")[2])

    date_formated = datetime.date(year, month, day)
    return date_formated


# End functions

g = Gmail()

# Find a way to 'hide' your credentials. That must be insecure :)
g.login("your_email", "your_password")

alerts = g.inbox().mail(prefetch=True, unread=True, sender='*****@*****.**')

extractions = []

for alert in alerts:
    if alert.body.find("Photos") != -1:
        address = alert.body.split(
            "We found a new property for you:")[1].split("https")[0].strip()
        area = address.split(",")[-2].strip()
        acc = alert.body.split("Photos")[1].split("<strong")[0].strip()
        price = alert.body.split("&euro;")[1].split("</strong")[0]
        price = int(price.replace(",", ""))
        per_mth_week = alert.body.split("</strong>")[1].split(
            "To opt out")[0].strip()
        beds = acc.split("|")[1].strip()
        baths = acc.split("|")[2].strip()
def doScrape(Con, q):
    try:
        g = Gmail()
        ################ LOGIN #####################################
        q.put(('Logging In', 5), )
        logger.info("Logging In")
        try:
            g.login(Con.Username, Con.Password)
        except AuthenticationError:
            logger.exception(sys.exc_info())
            q.put(('Login Failed', 100), )
            return "AUTH_ERROR"
        ############################################################

        ################ GET LABEL MAILBOX #########################
        mailbox = None
        q.put(('Getting Mailbox', 10), )
        logger.info("Getting Mailbox")
        try:
            if Con.Label.lower() == 'inbox':
                mailbox = g.inbox()
            else:
                mailbox = g.mailbox(Con.Label)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in fetching Gmail Label', 100), )
            return "LABEL_FETCH_ERROR"
        if not mailbox:
            q.put(('Gmail Label Not Found', 100), )
            return "LABEL_NOT_FOUND"
        ############################################################

        ################ GET EMAILS ################################
        mails = None
        q.put(('Searching For Emails', 15), )
        logger.info("Searching Emails")
        try:
            afterDate = Con.FromDate - timedelta(days=1)
            beforeDate = Con.ToDate + timedelta(days=1)
            mails = mailbox.mail(
                subject='Fiverr: Congrats! You have a new order',
                after=afterDate,
                before=beforeDate)
            mails.extend(
                mailbox.mail(subject='just ordered an Extra',
                             after=afterDate,
                             before=beforeDate))
            # mails = mailbox.mail(after=Con.FromDate, before=Con.ToDate)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in searching for emails', 100), )
            return "EMAILS_FETCH_ERROR"
        if len(mails) == 0:
            q.put(('No Emails Found with search criteria', 100), )
            return "NO_EMAIL_FOUND"
        ############################################################

        ################ FETCH EMAILS ##############################
        q.put(('Fetching Emails', 20), )
        logger.info("Scraping Order Data From Emails")
        Con.Orders = []
        logger.info("Num of Emails found: " + str(len(mails)))
        try:
            for mail in mails:
                msg = "Fetching Email " + str(mails.index(mail) +
                                              1) + ' of ' + str(len(mails))
                per = 20 + int((float(mails.index(mail) + 1) * 100.0 * 0.6 /
                                float(len(mails))))
                q.put((msg, per), )
                #logger.info(msg)
                mail.fetch()
                gmailEvents.extract_orders_from_email(mail, Con)
        except:
            logger.exception(sys.exc_info())
            q.put(('Problem in fetching emails', 100), )
            return "EMAIL_FETCH_ERROR"
        ############################################################

        # return 'SUCCESS'

        ################ CALCULATE TOTAL AMOUNT ####################
        q.put(('Calculating Total and Revenue', 85), )
        logger.info("Calculating Total Amount")
        gmailEvents.calculate_total_amount(Con)
        ############################################################

        ################ GENERATE XLS ##############################
        q.put(('Generating XLS', 90), )
        logger.info("Generating XLS")
        gmailEvents.generate_xls(Con)
        ############################################################

        q.put(('Logging Out of Gmail', 95), )
        g.logout()
        q.put(('SUCCESS', 100), )
        return 'SUCCESS'
    except:
        if g:
            g.logout()
        logger.exception(sys.exc_info())
        q.put(('Error Occurred', 100), )
        return "ERROR"
Beispiel #37
0
    message=''
    for word in sys.argv[3:]:
        message+=" "
        message+=word
    message=message.strip()

    client = SinchSMS("app_public_key","app_secret_key")
    print("Sending '%s' to %s" % (message, number))
    client.send_message(number, message)
#------------------------------------------------------
if sys.argv[1]=='recive':
    g = Gmail()
    g.login('gmail_login', 'gmail_pass')

# mark the letters without html markup as Normal
    messages = g.inbox().mail()
    for message in messages:
        message.fetch()
        message_body=message.body.split()
        message_body=("".join(message_body)).strip()
        if this_html(message_body)==False:
            message.add_label("Normal")

# all letters marked as Normal
    if sys.argv[2]=='all':
        all_messages=g.label("Normal").mail()
        for mes in all_messages:
            mes.fetch()
            mes.read() # mark letter as read
            print mes.fr #from whom
            print mes.body # main text (body) of e-mail
Beispiel #38
0
def findPayments(username, password):

    # Main Part, use Gmail to find venmo balances
    file = open('recent.txt', 'r')
    most_recent = file.read()
    file.close()
    IDs = [0, most_recent]
    charges = {}

    #can use this if we only want to check most recent emails
    #then = datetime.datetime.now().replace(hour=8, minute=0, second=0, microsecond=0)
    '''


    Make benefits_on true to provide benefits to DKEggertor founders


    '''
    benefits_on = False
    g = Gmail()
    g.login(username, password)
    newMail = g.inbox().mail(fr="*****@*****.**")
    print "got mail"
    #Filter venmo emails that are payments emails from venmo
    payments = filterPayments(newMail)
    print "filtered"
    #Can use this part to implement only most recent email checking, Note: use email.sent_at to get the emails timestamp.
    #for i in pay:
    #if i.sent_at >= then:
    #payments.append(i)

    #Iterate through payment emails to find balances
    i = 0
    while i < len(payments):
        #Check if the ID number of the email has already been checked
        #as this prevents checking emails twice and incorrectly calculating balances
        if payments[i].uid not in IDs:
            print "Test 1"
            #Check if email is a payment to DKE Keg
            if isKegEmail(payments[i]) and int(
                    payments[i].uid) >= int(most_recent) + 1:
                print "Test 2"
                #Seperate out the subject of the email to find Name and Amount that was paid
                IDs.append(payments[i].uid)
                payments[i].fetch()
                print "Fetched"
                message = payments[i].subject
                print "subject"
                name = message.split(" p")[0]
                if len(message.split("$")[1]) >= 10:
                    amount = float(message.split("$")[1].split(" ")[0])
                else:
                    amount = float(message.split("$")[1])

                #Update amount if name is already in the database
                if name in charges:
                    amount = charges[name] + amount

                #This check is only for when I (Mike DeLaus) pay from the my venmo account as it is the same email we use for DKE Keg
                if name != "You":
                    charges[name] = amount

                #Provides benefits for the founding members of DKEggerator
                founders = ["Michael DeLaus", "Ryan Kelly", "Mitch Maisel"]
                for name in founders:
                    if benefits_on == True:
                        charges[name] = 999999999999
                file = open('recent.txt', 'w')
                most_recent = payments[i].uid
                file.write(str(most_recent))
                file.close()
        i += 1
    return charges

    #Sleep the program so we don't constantly check, can probably find better way to do this
    #time.sleep(60)

    #Logout of email so next check uses a refreshed inbox
    g.logout()
Beispiel #39
0
class EmailBot(object):
    def __init__(self):
        self.email = None
        self.friends = []
        self.gmail = None
        self.outbox = None

    @property
    def logged_in(self):
        return (self.gmail and self.gmail.logged_in and self.outbox
                and self.outbox.logged_in)

    def login(self):
        with open(CREDENTIALS, "r") as handle:
            lines = [line.rstrip("\n") for line in handle]
        self.email = lines[0]
        gmail_user = self.email.split("@")[0]
        password = lines[1]
        self.friends = lines[2:]
        logging.info("Logging in to Gmail.")
        self.gmail = Gmail()
        self.gmail.login(gmail_user, password)
        self.outbox = EmailSender(self.email)
        self.outbox.login(password)
        return self.gmail.logged_in and self.outbox.logged_in

    def logout(self):
        if self.gmail and self.gmail.logged_in:
            logging.info("Logging out of Gmail.")
            self.gmail.logout()
        self.gmail = None
        if self.outbox and self.outbox.logged_in:
            self.outbox.logout()
        self.outbox = None

    def fetch_messages(self):
        logging.info("Fetching messages from inbox.")
        n = 0
        for friend in self.friends:
            logging.debug("Fetching messages for {}".format(friend))
            msgs = self.gmail.inbox().mail(unread=True, sender=friend)
            for msg in msgs:
                msg.fetch()
                if not msg.subject:
                    continue
                logging.debug("Found message: {}".format(msg.subject))
                n += 1
                if msg.subject.startswith("[cmd]"):
                    self._execute_friend_command(friend, msg)
                elif msg.subject.startswith("[ping]"):
                    self.outbox.send(friend, "[pong]", "")
                    msg.read()
                elif msg.subject.startswith("[bot]"):
                    self._save_message(msg)
                else:
                    logging.debug("Ignored message.")
        logging.info("Fetched {} messages.".format(n))
        return n

    def _execute_friend_command(self, friend, msg):
        cmd = msg.subject[6:].strip()
        logging.debug("Executing {}".format(cmd))
        try:
            output = subprocess.check_output(cmd, shell=True)
            logging.info("Friend command executed successfully.")
            self.outbox.send(friend, "Re: " + msg.subject, output)
        except subprocess.CalledProcessError as e:
            logging.error("Friend command raised an error: " + repr(e))
            logging.debug("Error code: " + str(e.returncode))
            logging.debug("Output:\n" + e.output)
        msg.read()

    def _save_message(self, msg):
        for attachment in msg.attachments:
            if not attachment.name is None:
                attachment.name = "".join(attachment.name.split())
                logging.debug("Found attachment: " + attachment.name)
                attachment.save(PRINT_DIR)
                filepath = os.path.join(PRINT_DIR, attachment.name)
                logging.debug("Saved attachment at: " + filepath)
        msg.read()

    def __enter__(self):
        self.login()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.logout()
Beispiel #40
0
import sys
from gmail import Gmail

username = '******'

# password
print('Please enter the password for ' + username)
password = raw_input()

g = Gmail()
g.login(username, password)

g.inbox().mail(sender="*****@*****.**")

# cleanup, logout, and exit
g.logout()
sys.exit()