Entrada de emails
This commit is contained in:
72
entry/email/inbox.py
Normal file
72
entry/email/inbox.py
Normal file
@ -0,0 +1,72 @@
|
||||
import argparse
|
||||
import imaplib
|
||||
import email
|
||||
|
||||
|
||||
# Email class that fetches emails from server by uid and can parse body for secretary, can also delete email by uid
|
||||
class Email:
|
||||
def __init__(self, uid):
|
||||
self.uid = uid
|
||||
self.message = ''
|
||||
|
||||
def get(self, imap):
|
||||
status, raw_data = imap.uid('fetch', self.uid, '(RFC822)')
|
||||
if status != 'OK':
|
||||
raise Exception('Could not recover message {0}'.format(self.uid))
|
||||
|
||||
self.message = email.message_from_bytes(raw_data[0][1])
|
||||
|
||||
def delete(self, imap):
|
||||
status, result = imap.uid('STORE', self.uid, '+FLAGS', '(\\Deleted)')
|
||||
if status != 'OK':
|
||||
raise Exception('Could not flag message {0}'.format(self.uid))
|
||||
|
||||
|
||||
def connect(imap_url, port, username, password, ssl=False):
|
||||
if ssl:
|
||||
server = imaplib.IMAP4_SSL(imap_url, port=port)
|
||||
else:
|
||||
server = imaplib.IMAP4(imap_url, port=port)
|
||||
server.login(username, password)
|
||||
return server
|
||||
|
||||
|
||||
def check_inbox(server):
|
||||
status, msg = server.select('INBOX')
|
||||
if status != 'OK':
|
||||
return None
|
||||
|
||||
status, ids = server.uid('search', None, 'All')
|
||||
if status != 'OK':
|
||||
return None
|
||||
|
||||
ids = ids[0].decode().split()
|
||||
emails = []
|
||||
for mid in ids:
|
||||
em = Email(mid)
|
||||
em.get(server)
|
||||
emails.append(em)
|
||||
|
||||
return emails
|
||||
|
||||
|
||||
def main(args):
|
||||
print('Connecting')
|
||||
imap_server = connect(imap_url=args.url, port=args.port, username=args.username, password=args.password,
|
||||
ssl=args.ssl)
|
||||
print('Checking emails')
|
||||
emails = check_inbox(imap_server)
|
||||
print(len(emails))
|
||||
[print(e) for e in emails]
|
||||
imap_server.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-u', '--url')
|
||||
parser.add_argument('-p', '--port')
|
||||
parser.add_argument('-un', '--username')
|
||||
parser.add_argument('-up', '--password')
|
||||
parser.add_argument('--ssl')
|
||||
_args = parser.parse_args()
|
||||
main(_args)
|
Reference in New Issue
Block a user