8000 Trailing Spaces Removed And Imports Imporved · Pull Request #41 · charlierguo/gmail · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Trailing Spaces Removed And Imports Imporved #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,13 @@ Download message attachments:
attachment.save('attachments/' + attachment.name)

There is also few shortcuts to mark messages quickly:

```python
email.read()
email.unread()
email.spam()
email.star()
email.unstar()
```

### Roadmap
* Write tests
Expand All @@ -142,7 +143,7 @@ There is also few shortcuts to mark messages quickly:

## Copyright

* Copyright (c) 2013 Charlie Guo
* Copyright (c) 2014 Charlie Guo

See LICENSE for details.

2 changes: 1 addition & 1 deletion gmail/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
__author__ = 'Charlie Guo'
__build__ = 0x0001
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Charlie Guo'
__copyright__ = 'Copyright 2014 Charlie Guo'

from .gmail import Gmail
from .mailbox import Mailbox
Expand Down
24 changes: 13 additions & 11 deletions gmail/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
# -*- coding: utf-8 -*-

"""
gmail.exceptions
~~~~~~~~~~~~~~~~~~~

This module contains the set of Gmails' exceptions.

"""


class GmailException(RuntimeError):
"""There was an ambiguous exception that occurred while handling your
request."""
"""
There was an ambiguous exception that occurred while handling your
request.
"""

8000 class ConnectionError(GmailException):
"""A Connection error occurred."""
"""
A Connection error occurred.
"""

class AuthenticationError(GmailException):
"""Gmail Authentication failed."""
"""
Gmail Authentication failed.
"""

class Timeout(GmailException):
"""The request timed out."""
"""
The request timed out.
"""
44 changes: 16 additions & 28 deletions gmail/gmail.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import re
import imaplib

import re,imaplib
from mailbox import Mailbox
from utf import encode as encode_utf7, decode as decode_utf7
from exceptions import *
Expand All @@ -9,7 +7,6 @@ class Gmail():
# GMail IMAP defaults
GMAIL_IMAP_HOST = 'imap.gmail.com'
GMAIL_IMAP_PORT = 993

# GMail SMTP defaults
# TODO: implement SMTP functions
GMAIL_SMTP_HOST = "smtp.gmail.com"
Expand All @@ -19,25 +16,21 @@ def __init__(self):
self.username = None
self.password = None
self.access_token = None

self.imap = None
self.smtp = None
self.logged_in = False
self.mailboxes = {}
self.current_mailbox = None


# self.connect()



def connect(self, raise_errors=True):
# try:
# self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT)
# except socket.error:
# if raise_errors:
# raise Exception('Connection failure.')
# self.imap = None

"""
try:
self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT)
except socket.error:
if raise_errors:
raise Exception('Connection failure.')
self.imap = None
"""
self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT)

# self.smtp = smtplib.SMTP(self.server,self.port)
Expand All @@ -50,6 +43,9 @@ def connect(self, raise_errors=True):


def fetch_mailboxes(self):
"""
Get mailbox from gmail
"""
response, mailbox_list = self.imap.list()
if response == 'OK':
for mailbox in mailbox_list:
Expand Down Expand Up @@ -91,32 +87,29 @@ def delete_mailbox(self, mailbox_name):


def login(self, username, password):
"""
Login to gmail server with users credentials
"""
self.username = username
self.password = password

if not self.imap:
self.connect()

try:
imap_login = self.imap.login(self.username, self.password)
self.logged_in = (imap_login and imap_login[0] == 'OK')
if self.logged_in:
self.fetch_mailboxes()
except imaplib.IMAP4.error:
raise AuthenticationError


# smtp_login(username, password)

return self.logged_in

def authenticate(self, username, access_token):
self.username = username
self.access_token = access_token

if not self.imap:
self.connect()

try:
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
imap_auth = self.imap.authenticate('XOAUTH2', lambda x: auth_string)
Expand All @@ -125,22 +118,19 @@ def authenticate(self, username, access_token):
self.fetch_mailboxes()
except imaplib.IMAP4.error:
raise AuthenticationError

return self.logged_in

def logout(self):
self.imap.logout()
self.logged_in = False


def label(self, label_name):
return self.mailbox(label_name)

def find(self, mailbox_name="[Gmail]/All Mail", **kwargs):
box = self.mailbox(mailbox_name)
return box.mail(**kwargs)


def copy(self, uid, to_mailbox, from_mailbox=None):
if from_mailbox:
self.use_mailbox(from_mailbox)
Expand All @@ -154,10 +144,8 @@ def fetch_multiple_messages(self, messages):
if re.search(r'UID (\d+)', raw_message[0]):
uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0]
messages[uid].parse(raw_message)

return messages


def labels(self, require_unicode=False):
keys = self.mailboxes.keys()
if require_unicode:
Expand Down
6 changes: 0 additions & 6 deletions gmail/mailbox.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from message import Message
from utf import encode as encode_utf7, decode as decode_utf7


class Mailbox():

def __init__(self, gmail, name="INBOX"):
Expand Down Expand Up @@ -72,7 +71,6 @@ def mail(self, prefetch=False, **kwargs):
for email in emails:
messages_dict[email.uid] = email
self.messages.update(self.gmail.fetch_multiple_messages(messages_dict))

return emails

# WORK IN PROGRESS. NOT FOR ACTUAL USE
Expand All @@ -81,13 +79,10 @@ def threads(self, prefetch=False, **kwargs):
response, data = self.gmail.imap.uid('SEARCH', 'ALL')
if response == 'OK':
uids = data[0].split(' ')


for uid in uids:
if not self.messages.get(uid):
self.messages[uid] = Message(self, uid)
emails.append(self.messages[uid])

if prefetch:
fetch_str = ','.join(uids)
response, results = self.gmail.imap.uid('FETCH', fetch_str, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)')
Expand All @@ -96,7 +91,6 @@ def threads(self, prefetch=False, **kwargs):
if re.search(r'UID (\d+)', raw_message[0]):
uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0]
self.messages[uid].parse(raw_message)

return emails

def count(self, **kwargs):
Expand Down
24 changes: 3 additions & 21 deletions gmail/message.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import datetime
import email
import re
import time
import os
import datetime,email,re,time,os
from email.header import decode_header, make_header
from imaplib import ParseFlags

class Message():



def __init__(self, mailbox, uid):
self.uid = uid
self.mailbox = mailbox
Expand Down Expand Up @@ -37,8 +32,6 @@ def __init__(self, mailbox, uid):

self.attachments = None



def is_read(self):
return ('\\Seen' in self.flags)

Expand Down Expand Up @@ -82,7 +75,6 @@ def remove_label(self, label):
self.gmail.imap.uid('STORE', self.uid, '-X-GM-LABELS', full_label)
if full_label in self.labels: self.labels.remove(full_label)


def is_deleted(self):
return ('\\Deleted' in self.flags)

Expand All @@ -100,14 +92,11 @@ def delete(self):
# self.gmail.imap.uid('STORE', self.uid, '-FLAGS', flag)
# if flag in self.flags: self.flags.remove(flag)


def move_to(self, name):
self.gmail.copy(self.uid, name, self.mailbox.name)
if name not in ['[Gmail]/Bin', '[Gmail]/Trash']:
self.delete()



def archive(self):
self.move_to('[Gmail]/All Mail')

Expand Down Expand Up @@ -166,20 +155,16 @@ def parse(self, raw_message):
if re.search(r'X-GM-MSGID (\d+)', raw_headers):
self.message_id = re.search(r'X-GM-MSGID (\d+)', raw_headers).groups(1)[0]


# Parse attachments into attachment objects array for this message
self.attachments = [
Attachment(attachment) for attachment in self.message._payload
if not isinstance(attachment, basestring) and attachment.get('Content-Disposition') is not None
]


def fetch(self):
if not self.message:
response, results = self.gmail.imap.uid('FETCH', self.uid, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)')

response, results = self.gmail.imap.uid('FETCH', self.uid, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)'
self.parse(results[0])

return self.message

# returns a list of fetched messages (both sent and received) in chronological order
Expand All @@ -206,13 +191,10 @@ def fetch_thread(self):
for uid in uids: sent_messages[uid] = Message(self.gmail.mailboxes['[Gmail]/Sent Mail'], uid)
self.gmail.fetch_multiple_messages(sent_messages)
self.gmail.mailboxes['[Gmail]/Sent Mail'].messages.update(sent_messages)

self.gmail.use_mailbox(original_mailbox.name)

# combine and sort sent and received messages
return sorted(dict(received_messages.items() + sent_messages.items()).values(), key=lambda m: m.sent_at)


class Attachment:

def __init__(self, attachment):
Expand Down
0