コード例 #1
0
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        socketio.emit('alert', 'Logging in as ' + USERNAME, Broadcast=True)
        select_info = server.select_folder(MAILBOX)
        socketio.emit('alert',
                      '%d messages in INBOX' % select_info[b'EXISTS'],
                      Broadcast=True)

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status[b'UNSEEN'])

    if DEBUG:
        socketio.emit('alert',
                      'You have' + str(newmails) + 'new emails!',
                      Broadcast=True)

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)
コード例 #2
0
def startService():
    try:
        while True:
            try:
                gServer = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
                gServer.login(USERNAME, PASSWORD)

                if DEBUG:
                    print('Logged in as ' + USERNAME)
                    select_info = gServer.select_folder(MAILBOX)
                    print('%d messages in INBOX' % select_info[b'EXISTS'])

                folder_status = gServer.folder_status(MAILBOX, 'UNSEEN')
                newmails = int(folder_status[b'UNSEEN'])

                if DEBUG:
                    print("You have %d new emails" % newmails)

                if newmails > 0:
                    notifyUser(newmails)

                time.sleep(MAIL_CHECK_FREQ)
            except Exception as e:
                if NOTIFY_ON_NO_INT_CONN:
                    print(e)
                else:
                    pass
    except KeyboardInterrupt:
        print("Service being closed by user")
コード例 #3
0
def loop():
    global FIRST_TIME
    global NEWMAIL_OFFSET
    
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Loggin in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if FIRST_TIME:
        FIRST_TIME = False
        NEWMAIL_OFFSET = newmails
        print('first time and newmail_offset is ', NEWMAIL_OFFSET)

    if newmails > NEWMAIL_OFFSET:
        print('newmails is ', newmails, ' and newmailoffset is ', NEWMAIL_OFFSET)
        NEWMAIL_OFFSET = newmails
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
        if DEBUG:
            print "You have", newmails, "New emails"
    else:
        print('in else and newmail_offset is ', NEWMAIL_OFFSET)
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)
        

    server.logout()
    time.sleep(MAIL_CHECK_FREQUENCY)
def mail_check():
    # login to mailserver
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    #fetch from address

    # select our MAILBOX and looked for unread messages
    unseen = server.folder_status(MAILBOX, ['UNSEEN'])

    # number of unread messages
    # print to console to determine NEWMAIL_OFFSET
    newmail_count = (unseen[b'UNSEEN'])
    print('%d unseen messages' % newmail_count)
    lcd.clear()
    lcd.message = '%d IN INBOX' % newmail_count
    time.sleep(5.0)
    lcd.clear()

    if newmail_count > NEWMAIL_OFFSET:
        lcd_line1 = 'NEW MAIL'
        time.sleep(5.0)
        lcd.clear()

    else:
        lcd.message = 'NO NEW MAIL'
        time.sleep(5.0)
        lcd.clear()

    time.sleep(MAIL_CHECK_FREQ)
コード例 #5
0
def loop():
    global oldmails

    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
 
    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])
 
    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])


    if DEBUG:
        print "You have", newmails, "new emails!"
 
    if newmails > oldmails:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)
 
    time.sleep(MAIL_CHECK_FREQ)
    oldmails = newmails
コード例 #6
0
ファイル: checkMail.py プロジェクト: sw-maestro-ichai/alarm
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if newmails >= 1:
        print "Exist new mail!!!!"
      	subprocess.call('bash /home/pi/alarm/ShellScript/checkEmail.sh', shell=True)

    if DEBUG:
        print "You have", newmails, "new emails!"

    if newmails > NEWMAIL_OFFSET:
        print "test1"

    else:
        print "test2"
    time.sleep(MAIL_CHECK_FREQ)
コード例 #7
0
ファイル: get_email.py プロジェクト: vihellor/alarma
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "tienes ", newmails, " correos nuevos en tu bandeja"
コード例 #8
0
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "tienes ", newmails, " correos nuevos en tu bandeja"
コード例 #9
0
def mail_check():
    # login to mailserver
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    # select our MAILBOX and looked for unread messages
    unseen = server.folder_status(MAILBOX, ['UNSEEN'])
    newmail_count = (unseen[b'UNSEEN'])
    print('%d unseen messages' % newmail_count)

    select_info = server.select_folder('INBOX')
    print('%d messages in INBOX' % select_info[b'EXISTS'])

    messages_from_kerem = server.search(['FROM', FROM_KEREM])
    print("%d messages from Kerem" % len(messages_from_kerem))

    messages_from_thomas = server.search(['FROM', FROM_THOMAS])
    print("%d messages from Thomas" % len(messages_from_thomas))

    if len(messages_from_kerem) > 0:
        for mail_id, data in server.fetch(messages_from_kerem,
                                          ['ENVELOPE', 'BODY[TEXT]']).items():
            envelope = data[b'ENVELOPE']
            body = data[b'BODY[TEXT]']
            print("%d messages from Kerem" % len(messages_from_kerem))
            print('ID #%d: "%s" ' % (mail_id, envelope.subject.decode()))
            if envelope.subject.decode() == "Temp":
                cmd_beginning = 'echo Temp = '
                cmd_end = 'C | msmtp ' + FROM_KEREM
                cmd_temp = read_temp()
                cmd = cmd_beginning + cmd_temp + cmd_end
                os.system(cmd)
                server.delete_messages(mail_id, False)
                print("Mail deleted")

    if len(messages_from_thomas) > 0:
        for mail_id, data in server.fetch(messages_from_thomas,
                                          ['ENVELOPE', 'BODY[TEXT]']).items():
            envelope = data[b'ENVELOPE']
            body = data[b'BODY[TEXT]']
            print("%d messages from Thomas" % len(messages_from_thomas))
            print('ID #%d: "%s" ' % (mail_id, envelope.subject.decode()))
            if envelope.subject.decode() == "Temp":
                cmd_beginning = 'echo Temp = '
                cmd_end = 'C | msmtp ' + FROM_THOMAS
                cmd_temp = read_temp()
                cmd = cmd_beginning + cmd_temp + cmd_end
                os.system(cmd)
                server.delete_messages(mail_id, False)
                print("Mail deleted")
コード例 #10
0
def loop():

    global USERNAME, PASSWORD, MAILBOX, HOSTNAME, lcd

    lcd.lcd_clear()
    lcd.lcd_display_string('Please tap your card', 1)
    id, text = reader.read()
    if id == 142668869250:
        USERNAME = USERNAME + "*****@*****.**"
        PASSWORD = PASSWORD + "shatxyajdcfminry"
        MAILBOX = MAILBOX + "Inbox"
    else:
        USERNAME = "******"
        PASSWORD = "******"
        MAILBOX = "Inbox"
    lcd.lcd_clear()
    lcd.lcd_display_string('Hello ' + text, 1)
    time.sleep(1)
    lcd.lcd_clear()
    lcd.lcd_display_string('Connecting to...', 1)
    lcd.lcd_display_string(USERNAME, 2)

    time.sleep(1)
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    messages = server.search('UNSEEN')
    newemail = server.fetch(messages, 'RFC822').items()[0][1]['RFC822']
    subject = re.search('.*Subject: (.*?)\\r\\n.*', newemail)
    lcd.lcd_display_string(subject.group(0))

    time.sleep(5)

    lcd.lcd_clear()
    lcd.lcd_display_string("You have " + str(newmails) + " new email/s!", 1)
    time.sleep(1)
    lcd.lcd_clear()

    time.sleep(MAIL_CHECK_FREQ)
コード例 #11
0
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])
    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])
    if DEBUG:
        print "You have", newmails, "new emails!"
    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)
    time.sleep(MAIL_CHECK_FREQ)
コード例 #12
0
ファイル: imapMails.py プロジェクト: rishigb/EmailHacks
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "You have", newmails, "new emails!"

    if newmails > NEWMAIL_OFFSET:
	print "emails undread here"
    time.sleep(MAIL_CHECK_FREQ)
コード例 #13
0
ファイル: mail_rec.py プロジェクト: Magu662/Project_Box
def mail_check():
    # login to mailserver
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    # select our MAILBOX and looked for unread messages
    unseen = server.folder_status(MAILBOX, ['UNSEEN'])

    # number of unread messages
    # print to console to determine NEWMAIL_OFFSET
    newmail_count = (unseen[b'UNSEEN'])
    print('%d unseen messages' % newmail_count)

    if newmail_count > 0:

        print('recived')
    # os.system("cd /home/pi/del.py")
    time.sleep(MAIL_CHECK_FREQ)
コード例 #14
0
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "You have", newmails, "new emails!"

    if newmails > NEWMAIL_OFFSET:
        os.system(
            'sudo -u pi zenity --info --text="You just received an email." --icon-name=emblem-mail --title="Email Checker" --no-wrap'
        )
コード例 #15
0
def CheckEmail():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    print('Logging in as ' + USERNAME)
    select_info = server.select_folder(MAILBOX)
    print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    print "You have", newmails, "new emails!"

    if newmails >= NEWMAIL_OFFSET:
        LED_On()
    else:
        LED_Off()

    time.sleep(MAIL_CHECK_FREQ)
コード例 #16
0
def CheckEmail():
	server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
	server.login(USERNAME, PASSWORD)
	
	print('Logging in as ' + USERNAME)
	select_info = server.select_folder(MAILBOX)
	print('%d messages in INBOX' % select_info['EXISTS'])
 
	folder_status = server.folder_status(MAILBOX, 'UNSEEN')
	newmails = int(folder_status['UNSEEN'])
 
	print "You have", newmails, "new emails!"
 
	if newmails >= NEWMAIL_OFFSET:
		LED_On()
	else:
		LED_Off()
		
	time.sleep(MAIL_CHECK_FREQ)
コード例 #17
0
def mailcheck_func():
    # Login credentials
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
    b'[CAPABILITY IMAP4rev1 LITERAL+ SAL-IR [...] LIST-STATUS QUOTA] Logged in'

    # Select folder and search for the unread messages
    select_info = server.select_folder(MAILBOX, readonly=True)
    unread = server.folder_status(MAILBOX, ['UNSEEN'])
    messages = server.search('UNSEEN')

    for uid, message_data in server.fetch(messages, 'RFC822').items():
        #print('enter here')
        email_message = email.message_from_bytes(message_data[b'RFC822']) 
        #print('this is email message %s' % (email_message))
        ##print('this is email message %s' % (email_message))
        if (not email_message):
          print('No new message in the Inbox')
          continue
        else:
            mail_sub = email_message.get('Subject') 
#            print('New email')  

####  adding new lines
#           Print total count of unread messages
            newmail_count = (unread[b'UNSEEN'])
            print('%d unread messages in the Inbox' % newmail_count)
####
            if (mail_sub):
              if (SUBJECT_KEYWORD in mail_sub):
                print('There is a Severity-1 case in Queue.')  
####
                speech=gTTS("Hello Heera..., Please check there is a Severity-1 case in the queue.")
                speech.save("Hello.mp3")
                os.system("mpg321 -q Hello.mp3")
####
              else:
                #print('There is no Sev-1')
                print(' ')
            else:
              print('There is no mail')

            print('')
コード例 #18
0
def mail_check():
    # login to mailserver
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    # select our MAILBOX and looked for unread messages
    unseen = server.folder_status(MAILBOX, ['UNSEEN'])

    # number of unread messages
    # print to console to determine NEWMAIL_OFFSET
    newmail_count = (unseen[b'UNSEEN'])
    print('%d unseen messages' % newmail_count)

    if newmail_count > NEWMAIL_OFFSET:
        green_led.value = True
        red_led.value = False
    else:
        green_led.value = False
        red_led.value = True

    time.sleep(MAIL_CHECK_FREQ)
コード例 #19
0
ファイル: email_test3.py プロジェクト: shmathew511/csc59866
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print ("You have") + newmails + ("new emails!")

    if newmails > NEWMAIL_OFFSET:
        system('say You have new mail.')
    else:
        system('say You do not have new mail.')

    time.sleep(MAIL_CHECK_FREQ)
コード例 #20
0
ファイル: checkmail.py プロジェクト: krajcovic/checkmail
def loop(username, password):
    server = IMAPClient(HOSTNAME, use_uid=True)
    # print(username, password)
    server.login(username, password)

    if DEBUG:
        print('Logging in as ' + username)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print("You have", newmails, "new emails!")

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)
コード例 #21
0
def loop():
  try:  
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
    
    select_info = server.select_folder(MAILBOX) 

    if DEBUG:
        print('Logging in as ' + USERNAME)
        print('%d messages in "Secret messages"' % select_info['EXISTS'])
 
    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])
 
    if DEBUG:
        print "You have", newmails, "new recent emails!"


    messages = server.search(['UNSEEN']) #NOT DELETED to see all email available 

    if DEBUG:
        print("There are %d messages that aren't read" % len(messages))  
        print("Messages:")

    response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE'])
    mail_array = []
    
    for msgid, data in response.iteritems():
        if DEBUG:
            print('   ID %d: %d bytes, flags=%s' % (msgid, data[b'RFC822.SIZE'], data[b'FLAGS']))    
        mail_array.append(msgid)
    
    if DEBUG:
       for elements  in mail_array:
           print(elements)
       

    
    if newmails > NEWMAIL_OFFSET:
        strip.setPixelColorRGB(0,0,0,255) #turn blue our neopixel if we have something to print
        strip.show()


        printer.wake()    
        time.sleep(5)
        printer.feed(1)

        for elements in mail_array:
            if printer.hasPaper() == True: #verify is printer has paper before printing.
               body = server.fetch(elements,['BODY.PEEK[1]']) #IMPORTANT you might have problems with these, try using "1", "1.1", "1.2" or "2". 
               if DEBUG:
                  print(body) #prints in console original text.
                  print(' ')
               body2 = decode_email(str(body)) #process the received text.
               if DEBUG:
                  print (body2) #prints in console processed text.
               #ticket_summary(body2) #call the ticket printing routine
               printer.println(body) #prints in paper the original text of the email. Change to "body2" for printing the processed version.
               if printer.hasPaper() == True: #verify is printer has paper after printing.
                  server.add_flags(elements, '\\Seen')  #mark as read if printed sucesfully.
               else:
                  strip.setPixelColorRGB(0,255,255,0) #show yellow neopixel if there is no paper in the printer.
                  strip.show()
                  if DEBUG:
                     print 'There is no paper in the printer.'
               if DEBUG:
                  print(' ')
                  time.sleep(12)
            else:
              strip.setPixelColorRGB(0,255,255,0) #show yellow neopixel if there is no paper in the printer.
              strip.show()
              if DEBUG:
                 print 'There is no paper in the printer.'
        printer.sleep() 
        
    else:
        strip.setPixelColorRGB(0,255,0,0) #show red neopixel if there are no emails for printing.
        strip.show()
        
  except:
    strip.setPixelColorRGB(0,255,0,255) #show purple neopixel if an error occurs reading the email.
    strip.show()
    if DEBUG:
        print 'Cant check email or an error has ocurred. Verify your internet conection or this script parameters'
コード例 #22
0
GPIO.setmode(GPIO.BCM)
GREEN_LED = 18
RED_LED = 23
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)

while True:
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "You have", newmails, "new emails!"

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)

GPIO.cleanup()
コード例 #23
0
                except:
                    print('Cant login to ' + login)
                    send_osd(ip, "Konto E-Mail:", "",
                             "Nie mogę się zalogować do: " + login, "",
                             picture, "", "", timeout, "")

                else:
                    if debug:
                        print('Logging in as ' + login)

                    select_info = imapserver.select_folder(mailbox)

                    if debug:
                        print('%d messages in INBOX' % select_info['EXISTS'])

                    folder_status = imapserver.folder_status(mailbox, 'UNSEEN')
                    newmails = int(folder_status['UNSEEN'])

                    if debug:
                        print "Account have", newmails, "new emails!"

                    if newmails > current_mails[cleanlogin]:
                        current_mails[cleanlogin] = newmails
                        if debug:
                            print "Sending notification about new emails!"
                        send_osd(ip, "Konto E-Mail:", "", login,
                                 str(newmails) + " nowych wiad.", picture, "",
                                 "", timeout, "")
                    else:
                        current_mails[cleanlogin] = newmails
                        if debug:
コード例 #24
0
ファイル: hedwig.py プロジェクト: JorgePe/randomideas
hub_tx_handle = hub_tx.valHandle
hub_rx = hub_svcs.getCharacteristics(UUID(RX_CHARACTERISTIC))[0]
hub_rx_handle = hub_rx.valHandle

#we are so lazy the don't care for messages comming from Hub and keep notifications OFF
#hub.writeCharacteristic(hub_tx_handle + 1, b'\x01\x00', withResponse=False)

print("Hub initialized")

# IMAP Client Initialization
server = IMAPClient(HOST, use_uid=True, ssl=True)
server.login(USERNAME, PASSWORD)
server.select_folder('INBOX', readonly=True)

# get the UID of the last mail at mailbox so we we know when a new one arrived
last_uid = server.folder_status('INBOX')[b'UIDNEXT']
#print("Last UID:", last_uid)

print("IMAP Client initialized")

# now keep checking for new mails and do the magic
while True:
    # check mailbox
    #    print("Checking Mail...")
    new_last_uid = server.folder_status('INBOX')[b'UIDNEXT']
    #    print(new_last_uid)
    if new_last_uid != last_uid:
        print("Got Mail")
        last_uid = new_last_uid
        send_command(hub, hub_rx_handle, CMD_LEFT)
        sleep(NOTICATION_TIME)
コード例 #25
0
class Connection(object):
    _server = None
    _credentials = None
    _username = None
    _folder = None
    _imapobj = None

    """   
    #From oauth2gmail.py -----------------------
    class GMailOAuth2Mixin(object):
        _credentials = None
        _username = None
    
        @staticmethod
        def refresh_credentials(credentials):
            authorized_http = credentials.authorize(http)
            for n in range(5):
                try:
                    credentials.refresh(authorized_http)
                    break
                except AccessTokenRefreshError:
                    sleep((2 ** n) + random.randint(0, 1000) / 1000)
            return credentials
    
        @staticmethod
        def generate_xoauth2_string(username, access_token):
            return 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
    
        def _get_oauth_string(self, username, credentials):
            if credentials.invalid or credentials.access_token_expired or credentials.access_token is None:
                credentials = self.refresh_credentials(credentials)
    
            self._credentials = credentials
            self._username = username
    
            auth_string = self.generate_xoauth2_string(username=username,
                                                       access_token=credentials.access_token)
            return auth_string

    class GMail_IMAP(imaplib.IMAP4_SSL, GMailOAuth2Mixin):
        def __init__(self, host=IMAP_HOST, port=IMAP_PORT, **kwargs):
            imaplib.IMAP4_SSL.__init__(self, host, port, **kwargs)
    
        def login_oauth2(self, username, credentials):
            auth_string = self._get_oauth_string(username, credentials)
            self.authenticate("XOAUTH2", lambda x: auth_string)
            return self._credentials
    #---------------------
    """
    
    #From: https://gist.github.com/miohtama/5389146
    @staticmethod
    def _get_decoded_email_body(msg):
        """ Decode email body.
     
        Detect character set if the header is not set.
     
        We try to get text/plain, but if there is not one then fallback to text/html.
     
        :param message_body: Raw 7-bit message body input e.g. from imaplib. Double encoded in quoted-printable and latin-1
     
        :return: Message body as unicode string
        """
     
        text = ""
        if msg.is_multipart():
            html = None
            for part in msg.get_payload():
     
                print "%s, %s" % (part.get_content_type(), part.get_content_charset())
     
                if part.get_content_charset() is None:
                    # We cannot know the character set, so return decoded "something"
                    text = part.get_payload(decode=True)
                    continue
     
                charset = part.get_content_charset()
     
                if part.get_content_type() == 'text/plain':
                    text = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')
     
                if part.get_content_type() == 'text/html':
                    html = unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')
     
            if text is not None:
                return text.strip()
            else:
                return html.strip()
        else:
            text = unicode(msg.get_payload(decode=True), msg.get_content_charset(), 'ignore').encode('utf8', 'replace')
            return text.strip()
        
    def _check_credentials(self, credentials):
        if credentials.invalid or credentials.access_token_expired or credentials.access_token is None:
            authorized_http = credentials.authorize(http)
            for n in range(5):
                try:
                    print "Refreshing\n"
                    credentials.refresh(authorized_http)
                    break
                except AccessTokenRefreshError:
                    print "Refresh failed: " + str(n) + "\n"
                    sleep((2 ** n) + random.randint(0, 1000) / 1000)
        return credentials
    
    def __init__(self, user, credentials):                      #Should be changed to take user instead of username for consitency
        #Authenticate using oauth2gmail functionality
        #self._imapobj = self.GMail_IMAP('imap.gmail.com')        
        #self._credentials = self._imapobj.login_oauth2(username, credentials)
        
        self._credentials = self._check_credentials(credentials)
        self._username = user.gmailuserinfo.gmail_username
        self._folder = user.gmailuserinfo.all_folder
        
        
        self._server = IMAPClient(IMAP_HOST, use_uid=True, ssl=True)
        
        #Maybe patch line 159 of imapclient.py from:
        #auth_string = lambda x: 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)
        #to an adaptation from the following from oauth2gmail:
        #self.docmd("AUTH", "XOAUTH2 %s" % base64.b64encode(auth_string))
        self._server.oauth2_login(self._username, self._credentials.access_token)
        self._server.select_folder(self._folder)
        
    def create(self, mail):
        #Don't support creating of gmails
        pass
    
    def update(self, mail_id, mail):
        serverTags = self._server.get_gmail_labels(mail_id)[mail_id]
        serverSpecialTags = list(filter(lambda x: x.startswith("\\"), serverTags))
        
        tags = [tag['tag'].decode('utf-8') for tag in mail.content['tags']]
        
        #tags = mail.content['tags']
        tags.extend(serverSpecialTags)
        
        self._server.set_gmail_labels(mail_id, tags)
        
        
    def read(self, mail_id):
        result = self._server.fetch(mail_id, ['RFC822', 'X-GM-LABELS'])
        
        #message = result[message_id]['RFC822']
        message = email.message_from_string(result[mail_id]['RFC822'])
        body = self._get_decoded_email_body(message)
        serverTags = result[mail_id]['X-GM-LABELS']
        noSpecialTags = filter(lambda x: not(x.startswith("\\")), serverTags)
        tags = [{'tag': tag.encode('utf-8')} for tag in noSpecialTags]

        mail = Mail(subject=message['Subject'], body=body, sender=message['From'], tags=tags)
        
        return mail
    
    def read_updated(self, mail_id, updated_since=None):
        if updated_since:
            result = self._server.fetch(mail_id, ['RFC822', 'X-GM-LABELS', 'MODSEQ'], ['CHANGEDSINCE ' + str(updated_since)])
        else:
            result = self._server.fetch(mail_id, ['RFC822', 'X-GM-LABELS', 'MODSEQ'])
        
        result_content = result.get(mail_id)
        
        if result_content:
            message = email.message_from_string(result_content['RFC822'])
            body = self._get_decoded_email_body(message)
            
            serverTags = result_content['X-GM-LABELS']
            noSpecialTags = filter(lambda x: not(x.startswith("\\")), serverTags)
            tags = [{'tag': tag.encode('utf-8')} for tag in noSpecialTags]
            
            last_update = result_content['MODSEQ'][0]      #Strangely returns tuple so have to index the first (and only during initial testing) part
    
            mail = Mail(subject=message['Subject'], body=body, sender=message['From'], tags=tags)
        
            return mail, last_update
        else:
            return None
        
    def find(self, query):
        messages = self._server.gmail_search(query)
        
        return messages
    
    def find_updated(self, query, updated_since=None):
        if updated_since:
            messages = self._server.search(['MODSEQ ' + str(updated_since)  , 'X-GM-RAW ' + query])
        else:
            messages = self._server.search(['X-GM-RAW ' + query])
        
        return messages
    
    def find_updated_excepted(self, query, updated_since=None, excepted_ids=[]):
        messages = self.find_updated(query, updated_since)
        filtered_messages = [ i for i in messages if i not in excepted_ids]
        
        return filtered_messages
    
    def latest_update_status(self):
        status = self._server.folder_status(self._folder, ('HIGHESTMODSEQ'))
        
        return status['HIGHESTMODSEQ']
        
コード例 #26
0
GPIO.setmode(GPIO.BCM) #BCM dizilimini ayarla
GREEN_LED = 4 #Yesil Led
RED_LED = 17 #Kirmizi Led
GPIO.setup(GREEN_LED, GPIO.OUT) #led cikisi
GPIO.setup(RED_LED, GPIO.OUT) #led cikisi

while True: #sonsuz dongu
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=False) #maile baglanti
    server.login(USERNAME, PASSWORD) #login ol

    if DEBUG:
        print('Giris yapildi >> ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d adet mail var!' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN') # okunmamis mail kontrolu
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print newmails, "yeni mail!"

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True) #led kontrolleri
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)

GPIO.cleanup()
コード例 #27
0
sense.load_image("hello.png")

try:
      server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
      server.login(USERNAME, PASSWORD)
except:
      connected = False
      sense.load_image("error.png")
else:
      connected = True
      sense.load_image("done.png")
      select_info = server.select_folder(MAILBOX)

try:
      while connected:
            folder_status = server.folder_status(MAILBOX, 'UNSEEN')
            newmails = int(folder_status['UNSEEN'])
            if newmails > NEWMAIL_OFFSET:
                  newmails -= NEWMAIL_OFFSET
                  sense.show_message(str(newmails))
                  if newmails == 1:
                        sense.load_image("mail.png")
                  elif newmails > 1 and newmails < 15 : 
                        sense.load_image("mailFew.png") 
                  elif newmails > 14:
                        sense.load_image("mailLot.png")
            else:
                  sense.load_image("nomail.png")
            time.sleep(MAIL_CHECK_FREQ)
except KeyboardInterrupt:
      pass
コード例 #28
0
class ImapDB(BaseDB):
    def __init__(self,
                 username,
                 password='******',
                 host='localhost',
                 port=143,
                 *args,
                 **kwargs):
        super().__init__(username, *args, **kwargs)
        self.imap = IMAPClient(host, port, use_uid=True, ssl=False)
        res = self.imap.login(username, password)
        self.cursor.execute(
            "SELECT lowModSeq,highModSeq,highModSeqMailbox,highModSeqThread,highModSeqEmail FROM account LIMIT 1"
        )
        row = self.cursor.fetchone()
        self.lastfoldersync = 0
        if row:
            self.lowModSeq,
            self.highModSeq,
            self.highModSeqMailbox,
            self.highModSeqThread,
            self.highModSeqEmail = row
        else:
            self.lowModSeq = 0
            self.highModSeq = 1
            self.highModSeqMailbox = 1
            self.highModSeqThread = 1
            self.highModSeqEmail = 1

        # (imapname, readonly)
        self.selected_folder = (None, False)
        self.mailboxes = {}
        self.sync_mailboxes()
        self.messages = {}

    def get_messages_cached(self, properties=(), id__in=()):
        messages = []
        if not self.messages:
            return messages, id__in, properties
        fetch_props = set()
        fetch_ids = set(id__in)
        for id in id__in:
            msg = self.messages.get(id, None)
            if msg:
                found = True
                for prop in properties:
                    try:
                        msg[prop]
                    except (KeyError, AttributeError):
                        found = False
                        fetch_props.add(prop)
                if found:
                    fetch_ids.remove(id)
                    messages.append(msg)
        # if one messages is missing, need to fetch all properties
        if len(messages) < len(id__in):
            fetch_props = properties
        return messages, fetch_ids, fetch_props

    def get_messages(self,
                     properties=(),
                     sort={},
                     inMailbox=None,
                     inMailboxOtherThan=(),
                     id__in=None,
                     threadId__in=None,
                     **criteria):
        # XXX: id == threadId for now
        if id__in is None and threadId__in is not None:
            id__in = [id[1:] for id in threadId__in]
        if id__in is None:
            messages = []
        else:
            # try get everything from cache
            messages, id__in, properties = self.get_messages_cached(
                properties, id__in=id__in)

        fetch_fields = {
            f
            for prop, f in FIELDS_MAP.items() if prop in properties
        }
        if 'RFC822' in fetch_fields:
            # remove redundand fields
            fetch_fields.discard('RFC822.HEADER')
            fetch_fields.discard('RFC822.SIZE')

        if inMailbox:
            mailbox = self.mailboxes.get(inMailbox, None)
            if not mailbox:
                raise errors.notFound(f'Mailbox {inMailbox} not found')
            mailboxes = [mailbox]
        elif inMailboxOtherThan:
            mailboxes = [
                m for m in self.mailboxes.values()
                if m['id'] not in inMailboxOtherThan
            ]
        else:
            mailboxes = self.mailboxes.values()

        search_criteria = as_imap_search(criteria)
        sort_criteria = as_imap_sort(sort) or '' if sort else None

        mailbox_uids = {}
        if id__in is not None:
            if len(id__in) == 0:
                return messages  # no messages matches empty ids
            if not fetch_fields and not sort_criteria:
                # when we don't need anything new from IMAP, create empty messages
                # useful when requested conditions can be calculated from id (threadId)
                messages.extend(
                    self.messages.get(id, 0) or ImapMessage(id=id)
                    for id in id__in)
                return messages

            for id in id__in:
                # TODO: check uidvalidity
                mailboxid, uidvalidity, uid = parse_message_id(id)
                uids = mailbox_uids.get(mailboxid, [])
                if not uids:
                    mailbox_uids[mailboxid] = uids
                uids.append(uid)
            # filter out unnecessary mailboxes
            mailboxes = [m for m in mailboxes if m['id'] in mailbox_uids]

        for mailbox in mailboxes:
            imapname = mailbox['imapname']
            if self.selected_folder[0] != imapname:
                self.imap.select_folder(imapname, readonly=True)
                self.selected_folder = (imapname, True)

            uids = mailbox_uids.get(mailbox['id'], None)
            # uids are now None or not empty
            # fetch all
            if sort_criteria:
                if uids:
                    search = f'{",".join(map(str, uids))} {search_criteria}'
                else:
                    search = search_criteria or 'ALL'
                uids = self.imap.sort(sort_criteria, search)
            elif search_criteria:
                if uids:
                    search = f'{",".join(map(str, uids))} {search_criteria}'
                uids = self.imap.search(search)
            if uids is None:
                uids = '1:*'
            fetch_fields.add('UID')
            fetches = self.imap.fetch(uids, fetch_fields)

            for uid, data in fetches.items():
                id = format_message_id(mailbox['id'], mailbox['uidvalidity'],
                                       uid)
                msg = self.messages.get(id, None)
                if not msg:
                    msg = ImapMessage(id=id, mailboxIds=[mailbox['id']])
                    self.messages[id] = msg
                for k, v in data.items():
                    msg[k.decode()] = v
                messages.append(msg)
        return messages

    def changed_record(self, ifolderid, uid, flags=(), labels=()):
        res = self.dmaybeupdate(
            'imessages', {
                'flags': json.dumps(sorted(flags)),
                'labels': json.dumps(sorted(labels)),
            }, {
                'ifolderid': ifolderid,
                'uid': uid
            })
        if res:
            msgid = self.dgefield('imessages', {
                'ifolderid': ifolderid,
                'uid': uid
            }, 'msgid')
            self.mark_sync(msgid)

    def import_message(self, rfc822, mailboxIds, keywords):
        folderdata = self.dget('ifolders')
        foldermap = {f['ifolderid']: f for f in folderdata}
        jmailmap = {
            f['jmailboxid']: f
            for f in folderdata if f.get('jmailboxid', False)
        }
        # store to the first named folder - we can use labels on gmail to add to other folders later.
        id, others = mailboxIds
        imapname = jmailmap[id][imapname]
        flags = set(keywords)
        for kw in flags:
            if kw in KEYWORD2FLAG:
                flags.remove(kw)
                flags.add(KEYWORD2FLAG[kw])
        appendres = self.imap.append('imapname', '(' + ' '.join(flags) + ')',
                                     datetime.now(), rfc822)
        # TODO: compare appendres[2] with uidvalidity
        uid = appendres[3]
        fdata = jmailmap[mailboxIds[0]]
        self.do_folder(fdata['ifolderid'], fdata['label'])
        ifolderid = fdata['ifolderid']
        msgdata = self.dgetone('imessages', {
            'ifolderid': ifolderid,
            'uid': uid,
        }, 'msgid,thrid,size')

        # XXX - did we fail to sync this back?  Annoying
        if not msgdata:
            raise Exception(
                'Failed to get back stored message from imap server')
        # save us having to download it again - drop out of transaction so we don't wait on the parse
        message = parse.parse(rfc822, msgdata['msgid'])
        self.begin()
        self.dinsert(
            'jrawmessage', {
                'msgid': msgdata['msgid'],
                'parsed': json.dumps('message'),
                'hasAttachment': message['hasattachment'],
            })
        self.commit()
        return msgdata

    def update_messages(self, changes, idmap):
        if not changes:
            return {}, {}

        changed = {}
        notchanged = {}
        map = {}
        msgids = set(changes.keys())
        sql = 'SELECT msgid,ifolderid,uid FROM imessages WHERE msgid IN (' + (
            ('?,' * len(msgids))[:-1]) + ')'
        self.cursor.execute(sql, list(msgids))
        for msgid, ifolderid, uid in self.cursor:
            if not msgid in map:
                map[msgid] = {ifolderid: {uid}}
            elif not ifolderid in map[msgid]:
                map[msgid][ifolderid] = {uid}
            else:
                map[msgid][ifolderid].add(uid)
            msgids.discard(msgid)

        for msgid in msgids:
            notchanged[msgid] = {
                'type': 'notFound',
                'description': 'No such message on server',
            }

        folderdata = self.dget('ifolders')
        foldermap = {f['ifolderid']: f for f in folderdata}
        jmailmap = {
            f['jmailboxid']: f
            for f in folderdata if 'jmailboxid' in f
        }
        jmapdata = self.dget('jmailboxes')
        jidmap = {d['jmailboxid']: (d['role'] or '') for d in jmapdata}
        jrolemap = {
            d['role']: d['jmailboxid']
            for d in jmapdata if 'role' in d
        }

        for msgid in map.keys():
            action = changes[msgid]
            try:
                for ifolderid, uids in map[msgid].items():
                    # TODO: merge similar actions?
                    imapname = foldermap[ifolderid]['imapname']
                    uidvalidity = foldermap[ifolderid]['uidvalidity']
                    if self.selected_folder != (imapname, False):
                        self.imap.select_folder(imapname)
                        self.selected_folder = (imapname, False)
                    if imapname and uidvalidity and 'keywords' in action:
                        flags = set(action['keywords'])
                        for kw in flags:
                            if kw in KEYWORD2FLAG:
                                flags.remove(kw)
                                flags.add(KEYWORD2FLAG[kw])
                        self.imap.set_flags(uids, flags, silent=True)

                if 'mailboxIds' in action:
                    mboxes = [idmap(k) for k in action['mailboxIds'].keys()]
                    # existing ifolderids containing this message
                    # identify a source message to work from
                    ifolderid = sorted(map[msgid])[0]
                    uid = sorted(map[msgid][ifolderid])[0]
                    imapname = foldermap[ifolderid]['imapname']
                    uidvalidity = foldermap[ifolderid]['uidvalidity']

                    # existing ifolderids with this message
                    current = set(map[msgid].keys())
                    # new ifolderids that should contain this message
                    new = set(jmailmap[x]['ifolderid'] for x in mboxes)
                    for ifolderid in new:
                        # unless there's already a matching message in it
                        if current.pop(ifolderid):
                            continue
                        # copy from the existing message
                        newfolder = foldermap[ifolderid]['imapname']
                        self.imap.copy(imapname, uidvalidity, uid, newfolder)
                    for ifolderid in current:
                        # these ifolderids didn't exist in new, so delete all matching UIDs from these folders
                        self.imap.move(
                            foldermap[ifolderid]['imapname'],
                            foldermap[ifolderid]['uidvalidity'],
                            map[msgid][ifolderid],  # uids
                        )
            except Exception as e:
                notchanged[msgid] = {'type': 'error', 'description': str(e)}
                raise e
            else:
                changed[msgid] = None

        return changed, notchanged

    def destroy_messages(self, ids):
        if not ids:
            return [], {}
        destroymap = defaultdict(dict)
        notdestroyed = {}
        idset = set(ids)
        rows = self.dget('imessages', {'msgid': ('IN', idset)},
                         'msgid,ifolderid,uid')
        for msgid, ifolderid, uid in rows:
            idset.discard(msgid)
            destroymap[ifolderid][uid] = msgid
        for msgid in idset:
            notdestroyed[msgid] = {
                'type': 'notFound',
                'description': "No such message on server",
            }

        folderdata = self.dget('ifolders')
        foldermap = {d['ifolderid']: d for d in folderdata}
        jmailmap = {
            d['jmailboxid']: d
            for d in folderdata if 'jmailboxid' in d
        }
        destroyed = []
        for ifolderid, ifolder in destroymap.items():
            #TODO: merge similar actions?
            if not ifolder['imapname']:
                for msgid in destroymap[ifolderid]:
                    notdestroyed[msgid] = \
                        {'type': 'notFound', 'description': "No folder"}
            self.imap.move(ifolder['imapname'], ifolder['uidvalidity'],
                           destroymap[ifolderid].keys(), None)
            destroyed.extend(destroymap[ifolderid].values())

        return destroyed, notdestroyed

    def deleted_record(self, ifolderid, uid):
        msgid = self.dgetfield('imessages', {
            'ifolderid': ifolderid,
            'uid': uid
        }, 'msgid')
        if msgid:
            self.ddelete('imessages', {'ifolderid': ifolderid, 'uid': uid})
            self.mark_sync(msgid)

    def get_raw_message(self, msgid, part=None):
        self.cursor.execute(
            'SELECT imapname,uidvalidity,uid FROM ifolders JOIN imessages USING (ifolderid) WHERE msgid=?',
            [msgid])
        imapname, uidvalidity, uid = self.cursor.fetchone()
        if not imapname:
            return None
        typ = 'message/rfc822'
        if part:
            parsed = self.fill_messages([msgid])
            typ = find_type(parsed[msgid], part)

        res = self.imap.getpart(imapname, uidvalidity, uid, part)
        return typ, res['data']

    def get_mailboxes(self, fields=None, **criteria):
        byimapname = {}
        # TODO: LIST "" % RETURN (STATUS (UNSEEN MESSAGES HIGHESTMODSEQ MAILBOXID))
        for flags, sep, imapname in self.imap.list_folders():
            status = self.imap.folder_status(imapname, ([
                'MESSAGES', 'UIDVALIDITY', 'UIDNEXT', 'HIGHESTMODSEQ', 'X-GUID'
            ]))
            flags = [f.lower() for f in flags]
            roles = [f for f in flags if f not in KNOWN_SPECIALS]
            label = roles[0].decode() if roles else imapname
            role = ROLE_MAP.get(label.lower(), None)
            can_select = b'\\noselect' not in flags
            byimapname[imapname] = {
                # Dovecot can fetch X-GUID
                'id': status[b'X-GUID'].decode(),
                'parentId': None,
                'name': imapname,
                'role': role,
                'sortOrder': 2 if role else (1 if role == 'inbox' else 3),
                'isSubscribed': True,  # TODO: use LSUB
                'totalEmails': status[b'MESSAGES'],
                'unreadEmails': 0,
                'totalThreads': 0,
                'unreadThreads': 0,
                'myRights': {
                    'mayReadItems': can_select,
                    'mayAddItems': can_select,
                    'mayRemoveItems': can_select,
                    'maySetSeen': can_select,
                    'maySetKeywords': can_select,
                    'mayCreateChild': True,
                    'mayRename': False if role else True,
                    'mayDelete': False if role else True,
                    'maySubmit': can_select,
                },
                'imapname': imapname,
                'sep': sep.decode(),
                'uidvalidity': status[b'UIDVALIDITY'],
                'uidnext': status[b'UIDNEXT'],
                # Data sync properties
                'createdModSeq': status[b'UIDVALIDITY'],  # TODO: persist
                'updatedModSeq':
                status[b'UIDVALIDITY'],  # TODO: from persistent storage
                'updatedNotCountsModSeq':
                status[b'UIDVALIDITY'],  # TODO: from persistent storage
                'emailHighestModSeq': status[b'HIGHESTMODSEQ'],
                'deleted': 0,
            }

        # set name and parentId for child folders
        for imapname, mailbox in byimapname.items():
            names = imapname.rsplit(mailbox['sep'], maxsplit=1)
            if len(names) == 2:
                mailbox['parentId'] = byimapname[names[0]]['id']
                mailbox['name'] = names[1]

        # update cache
        self.mailboxes = {mbox['id']: mbox for mbox in byimapname.values()}
        return byimapname.values()

    def sync_mailboxes(self):
        self.get_mailboxes()

    def mailbox_imapname(self, parentId, name):
        parent = self.mailboxes.get(parentId, None)
        if not parent:
            raise errors.notFound('parent folder not found')
        return parent['imapname'] + parent['sep'] + name

    def create_mailbox(self,
                       name=None,
                       parentId=None,
                       isSubscribed=True,
                       **kwargs):
        if not name:
            raise errors.invalidProperties('name is required')
        imapname = self.mailbox_imapname(parentId, name)
        # TODO: parse returned MAILBOXID
        try:
            res = self.imap.create_folder(imapname)
        except IMAPClientError as e:
            desc = str(e)
            if '[ALREADYEXISTS]' in desc:
                raise errors.invalidArguments(desc)
        except Exception:
            raise errors.serverFail(res.decode())

        if not isSubscribed:
            self.imap.unsubscribe_folder(imapname)

        status = self.imap.folder_status(imapname, ['UIDVALIDITY'])
        self.sync_mailboxes()
        return f"f{status[b'UIDVALIDITY']}"

    def update_mailbox(self,
                       id,
                       name=None,
                       parentId=None,
                       isSubscribed=None,
                       sortOrder=None,
                       **update):
        mailbox = self.mailboxes.get(id, None)
        if not mailbox:
            raise errors.notFound('mailbox not found')
        imapname = mailbox['imapname']

        if (name is not None and name != mailbox['name']) or \
           (parentId is not None and parentId != mailbox['parentId']):
            if not name:
                raise errors.invalidProperties('name is required')
            newimapname = self.mailbox_imapname(parentId, name)
            res = self.imap.rename_folder(imapname, newimapname)
            if b'NO' in res or b'BAD' in res:
                raise errors.serverFail(res.encode())

        if isSubscribed is not None and isSubscribed != mailbox['isSubscribed']:
            if isSubscribed:
                res = self.imap.subscribe_folder(imapname)
            else:
                res = self.imap.unsubscribe_folder(imapname)
            if b'NO' in res or b'BAD' in res:
                raise errors.serverFail(res.encode())

        if sortOrder is not None and sortOrder != mailbox['sortOrder']:
            # TODO: update in persistent storage
            mailbox['sortOrder'] = sortOrder
        self.sync_mailboxes()

    def destroy_mailbox(self, id):
        mailbox = self.mailboxes.get(id, None)
        if not mailbox:
            raise errors.notFound('mailbox not found')
        res = self.imap.delete_folder(mailbox['imapname'])
        if b'NO' in res or b'BAD' in res:
            raise errors.serverFail(res.encode())
        mailbox['deleted'] = datetime.now().timestamp()
        self.sync_mailboxes()

    def create_submission(self, new, idmap):
        if not new:
            return {}, {}

        todo = {}
        createmap = {}
        notcreated = {}
        for cid, sub in new.items():
            msgid = idmap.get(sub['emailId'], sub['emailId'])
            if not msgid:
                notcreated[cid] = {'error': 'nos msgid provided'}
                continue
            thrid = self.dgetfield('jmessages', {
                'msgid': msgid,
                'deleted': 0
            }, 'thrid')
            if not thrid:
                notcreated[cid] = {'error': 'message does not exist'}
                continue
            id = self.dmake(
                'jsubmission', {
                    'sendat':
                    datetime.fromisoformat()(sub['sendAt']).isoformat()
                    if sub['sendAt'] else datetime.now().isoformat(),
                    'msgid':
                    msgid,
                    'thrid':
                    thrid,
                    'envelope':
                    json.dumps(sub['envelope']) if 'envelope' in sub else None,
                })
            createmap[cid] = {'id': id}
            todo[cid] = msgid
        self.commit()

        for cid, sub in todo.items():
            type, rfc822 = self.get_raw_message(todo[cid])
            self.imap.send_mail(rfc822, sub['envelope'])

        return createmap, notcreated

    def update_submission(self, changed, idmap):
        return {}, {x: 'change not supported' for x in changed.keys()}

    def destroy_submission(self, destroy):
        if not destroy:
            return [], {}
        destroyed = []
        notdestroyed = {}
        namemap = {}
        for subid in destroy:
            deleted = self.dgetfield('jsubmission', {'jsubid': subid},
                                     'deleted')
            if deleted:
                destroy.append(subid)
                self.ddelete('jsubmission', {'jsubid': subid})
            else:
                notdestroyed[subid] = {
                    'type': 'notFound',
                    'description': 'submission not found'
                }
        self.commit()
        return destroyed, notdestroyed

    def _initdb(self):
        super()._initdb()

        self.dbh.execute("""
            CREATE TABLE IF NOT EXISTS ifolders (
            ifolderid INTEGER PRIMARY KEY NOT NULL,
            jmailboxid INTEGER,
            sep TEXT NOT NULL,
            imapname TEXT NOT NULL,
            label TEXT,
            uidvalidity INTEGER,
            uidfirst INTEGER,
            uidnext INTEGER,
            highestmodseq INTEGER,
            uniqueid TEXT,
            mtime DATE NOT NULL
            )""")
        self.dbh.execute(
            "CREATE INDEX IF NOT EXISTS ifolderj ON ifolders (jmailboxid)")
        self.dbh.execute(
            "CREATE INDEX IF NOT EXISTS ifolderlabel ON ifolders (label)")

        self.dbh.execute("""
            CREATE TABLE IF NOT EXISTS imessages (
            imessageid INTEGER PRIMARY KEY NOT NULL,
            ifolderid INTEGER,
            uid INTEGER,
            internaldate DATE,
            modseq INTEGER,
            flags TEXT,
            labels TEXT,
            thrid TEXT,
            msgid TEXT,
            envelope TEXT,
            bodystructure TEXT,
            size INTEGER,
            mtime DATE NOT NULL
            )""")
        self.dbh.execute(
            "CREATE UNIQUE INDEX IF NOT EXISTS imsgfrom ON imessages (ifolderid, uid)"
        )
        self.dbh.execute(
            "CREATE INDEX IF NOT EXISTS imessageid ON imessages (msgid)")
        self.dbh.execute(
            "CREATE INDEX IF NOT EXISTS imessagethrid ON imessages (thrid)")

        self.dbh.execute("""
            CREATE TABLE IF NOT EXISTS ithread (
            messageid TEXT PRIMARY KEY,
            sortsubject TEXT,
            thrid TEXT
            )""")
        self.dbh.execute(
            "CREATE INDEX IF NOT EXISTS ithrid ON ithread (thrid)")
コード例 #29
0
    def startECR(self):
        # Read user's email account info in user.txt
        acct = LoginInfo()

        try:
            #print(acct.HOSTNAME + " " + acct.USERNAME + " " + acct.PASSWORD)
            server = IMAPClient(acct.HOSTNAME, use_uid=True, ssl=True)
            server.login(acct.USERNAME, acct.PASSWORD)
        except:
            connected = False
            self.logging.info("ECR:: Error occurred while connecting")
            return

        connected = True
        select_info = server.select_folder(ECR.MAILBOX)
        self.logging.info("ECR connected")

        try:
            old_email_count = 0
            #self.logging.info("endEvent, isSet =" + str(self.end_event.is_set()))
            while (connected and not self.end_event.is_set()):
                folder_status = server.folder_status(ECR.MAILBOX, 'UNSEEN')
                newmails = int(folder_status[b'UNSEEN'])
                if (old_email_count > newmails
                    ):  #client has deleted some of their old mail, reset count
                    self.logging.info("emails being read detected")
                    old_email_count = 0
                elif (old_email_count == newmails):  #no new emails to output
                    pass
                    #print("no new emails to output")
                else:
                    delta = newmails - old_email_count
                    messages = server.search('UNSEEN')
                    last_check = datetime.datetime.now()
                    email_list = []

                    # Extracting unread emails from IMAP Server
                    self.extractEmailsFromIMAP(messages, email_list, server)

                    # sort by date received,newest 1st
                    email_list.sort(reverse=True, key=ECR.extractDate)

                    # implicit filtering, only read delta emails
                    for i in range(delta):
                        email_obj = email_list[i][1]
                        email_subj = email_obj.get('Subject').lower()
                        email_from = email_obj.get('From').lower()
                        email_body = None
                        email_multipart = []
                        if (email_obj.is_multipart()):
                            for payload in email_obj.get_payload():
                                email_multipart.append(
                                    payload.get_payload().lower())
                        else:
                            email_body = email_obj.get_payload().lower()
                        email_tuple = (email_subj, email_from, email_body,
                                       email_multipart)

                        self.put_email_in_queue(email_tuple)
                        # self.logging.info("ECR placed email content " + email_subj)
                    # Marking extracted emails as unread
                    old_email_count = newmails
                time.sleep(self.check_freq)

            end_of_loop_str = "ECR:: end of email polling loop, connection=" + str(
                connected) + " endEvent=" + str(self.end_event.is_set())
            self.logging.info(end_of_loop_str)
        except KeyboardInterrupt:
            self.logging.info("ECR::closing email client")
            self.end_event.set()
            server.remove_flags(self.to_mark_unread, [SEEN])
            self.to_mark_unread = []
            server.logout()
            return
        except Exception as e:
            raise e
コード例 #30
0
ファイル: main.py プロジェクト: H--o-l/Pi_flag_raiser
def main(argv):
  debug = False
  identification = ''
  password = ''
  new_mails_count = -1
  previous_new_mails_count = -1

  # Get identification and password from command line argument
  try:
    opts, args = getopt.getopt(argv,'hi:p:d',['identification=','password='******'debug'])
  except getopt.GetoptError:
    inputHelp()
  for opt, arg in opts:
    if opt == '-h':
      inputHelp()
    elif opt in ('-i', '--identification'):
      identification = arg
    elif opt in ('-p', '--password'):
      password = arg
    elif opt in ('-d', '--debug'):
      debug = True
    else:
      print opt + ' unknown option.'
      inputHelp()
  if identification == '' or password == '':
    inputHelp()

  print '#--- Start\nId is: ' + identification
  if debug:
    if INIT_WAIT != 0:
      print 'Waiting ' + str(INIT_WAIT) + 's before first connexion'

  # Init servo
  servo = PWM.Servo()

  # Test servo
  raiseFlag()
  lowerFlag()
  
  # Flush stdout for debug and sleep
  sys.stdout.flush()
  time.sleep(INIT_WAIT)

  try:
    # Loop
    while True:
      # New server and log in server (imap forbid server reopen)
      server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
      server.login(identification, password)

      # Unseen mail
      folder_status = server.folder_status(MAILBOX, 'UNSEEN')
      previous_new_mails_count = new_mails_count
      new_mails_count = int(folder_status['UNSEEN'])
      server.logout()

      if debug:
        print 'You have', new_mails_count, 'new emails'

      # IO update
      if previous_new_mails_count != new_mails_count:
        if new_mails_count > 0:
          raiseFlag()
        else:
          lowerFlag()

      # Flush stdout for debug and sleep
      sys.stdout.flush()
      time.sleep(MAIL_CHECK_FREQ)

  finally:
    print '#--- Stop'
    lowerFlag()
    time.sleep(SERVO_LATENCY)
コード例 #31
0
ファイル: start.py プロジェクト: Zer0R7/4962Project
def main():
    from sense_hat import SenseHat, ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED
    from imapclient import IMAPClient
    import time
    import sys
    from time import gmtime, strftime


    LOG = True
    HOSTNAME = 'imap.gmail.com'
    USERNAME = '******'
    PASSWORD = '******'
    MAILBOX = 'Inbox' 
    NEWMAIL_OFFSET = 0 
    MAIL_CHECK_FREQ = 5

    sense = SenseHat()
    sense.load_image("hello.png")

    def spinning_cursor():
        while True:
            for cursor in '|/-\\':
                yield cursor
    spinner = spinning_cursor()

    print("\n\n\n############# MAIL CHECKER SYSTEM ###########")
    print("#\n#")
    print('# Login:  '******'\b')
    try:
        server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
        server.login(USERNAME, PASSWORD)
    except:
        verif = False
        print ("Can not login check your configuration")
        sense.load_image("error.png")
    else:
        verif = True
        sense.load_image("done.png")
        select_info = server.select_folder(MAILBOX)
        print("# Connection Successful! \n#")
        
    print('#\n#')
    print("#############################################\n")
    time.sleep(2)
                    
    if verif == True:
        sense.load_image("up.png")
        folder_status = server.folder_status(MAILBOX, 'UNSEEN')
        newmails = int(folder_status['UNSEEN'])
        
        if LOG:
                print ('You have %d new emails.' % newmails)
                    
        if newmails > NEWMAIL_OFFSET:
            nbr = str(newmails)
            msgs = (nbr)
            sense.show_message(msgs)

            if newmails == 1:
                sense.load_image("mail.png")
            elif newmails > 1 and newmails < 15:
                sense.load_image("mailFew.png")
            elif newmails > 14:
                sense.load_image("mailLot.png")
            else:
                sense.load_image("nomail.png")
            
        time.sleep(MAIL_CHECK_FREQ)
        sense.clear()
        import MasterFile