Проблемы с IMAP в Gmail с Python - PullRequest
3 голосов
/ 26 июня 2011

У меня проблема с IMAP в Python 2.7 Для тестирования я создал foobar306@gmail.com с паролем testing123testing Я следую этому учебнику и набрал его в своей итеративной оболочке Python:

    Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('foobar306@gmail.com', 'testing123testing')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
>>> 

Ничего не происходит, даже сообщения об ошибках. Примечание. Я включил IMAP в Gmail. Спасибо, -tim

Обновление: в ответ на этот комментарий:

Вы делали следующий раздел после кода, который вы цитировали выше? - Янтарь

Я пробовал это:

    Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "ALL")

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0] # here's the body, which is raw text of the whole email
# including headers and alternate payloads

>>>

и он все еще ничего не сделал

1 Ответ

3 голосов
/ 26 июня 2011

Кажется, это работает для меня; Я создал папку sarnoldwashere через Python API:

>>> mail.create("sarnoldwashere")
('OK', ['Success'])
>>> mail.list()
('OK', ['(\\HasNoChildren) "/" "INBOX"',
'(\\HasNoChildren) "/" "Personal"',
'(\\HasNoChildren) "/" "Receipts"',
'(\\HasNoChildren) "/" "Travel"',
'(\\HasNoChildren) "/" "Work"',
'(\\Noselect \\HasChildren) "/" "[Gmail]"',
'(\\HasNoChildren) "/" "[Gmail]/All Mail"',
'(\\HasNoChildren) "/" "[Gmail]/Drafts"',
'(\\HasNoChildren) "/" "[Gmail]/Sent Mail"',
'(\\HasNoChildren) "/" "[Gmail]/Spam"',
'(\\HasNoChildren) "/" "[Gmail]/Starred"',
'(\\HasChildren \\HasNoChildren) "/" "[Gmail]/Trash"',
'(\\HasNoChildren) "/" "sarnoldwashere"'])
>>> mail.logout()
('BYE', ['LOGOUT Requested'])

Это все еще должно быть в веб-интерфейсе. (Пока кто-то еще не удалит его.)

Редактировать , чтобы включить полное содержание сеанса, даже включая скучные биты, где я заново изучаю Путь Python:

>>> import imaplib
>>> mail = imaplib.IMAP4_SSL('imap.gmail.com')
>>> mail.login('foobar306@gmail.com', 'testing123testing')
('OK', ['foobar306@gmail.com .. .. authenticated (Success)'])
>>> mail.list()
('OK', ['(\\HasNoChildren) "/" "INBOX"', '(\\HasNoChildren) "/" "Personal"', '(\\HasNoChildren) "/" "Receipts"', '(\\HasNoChildren) "/" "Travel"', '(\\HasNoChildren) "/" "Work"', '(\\Noselect \\HasChildren) "/" "[Gmail]"', '(\\HasNoChildren) "/" "[Gmail]/All Mail"', '(\\HasNoChildren) "/" "[Gmail]/Drafts"', '(\\HasNoChildren) "/" "[Gmail]/Sent Mail"', '(\\HasNoChildren) "/" "[Gmail]/Spam"', '(\\HasNoChildren) "/" "[Gmail]/Starred"', '(\\HasChildren \\HasNoChildren) "/" "[Gmail]/Trash"'])
>>> # Out: list of "folders" aka labels in gmail.
... mail.select("inbox") # connect to inbox.
('OK', ['3'])
>>> mail.dir()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/imaplib.py", line 214, in __getattr__
    raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
AttributeError: Unknown IMAP4 command: 'dir'
>>> dir(mail)
['PROTOCOL_VERSION', '_CRAM_MD5_AUTH', '__doc__', '__getattr__', '__init__', '__module__', '_append_untagged', '_check_bye', '_checkquote', '_cmd_log', '_cmd_log_idx', '_cmd_log_len', '_command', '_command_complete', '_dump_ur', '_get_line', '_get_response', '_get_tagged_response', '_log', '_match', '_mesg', '_new_tag', '_quote', '_simple_command', '_untagged_response', 'abort', 'append', 'authenticate', 'capabilities', 'capability', 'certfile', 'check', 'close', 'continuation_response', 'copy', 'create', 'debug', 'delete', 'deleteacl', 'error', 'expunge', 'fetch', 'getacl', 'getannotation', 'getquota', 'getquotaroot', 'host', 'is_readonly', 'keyfile', 'list', 'literal', 'login', 'login_cram_md5', 'logout', 'lsub', 'mo', 'mustquote', 'myrights', 'namespace', 'noop', 'open', 'partial', 'port', 'print_log', 'proxyauth', 'read', 'readline', 'readonly', 'recent', 'rename', 'response', 'search', 'select', 'send', 'setacl', 'setannotation', 'setquota', 'shutdown', 'sock', 'socket', 'sort', 'ssl', 'sslobj', 'state', 'status', 'store', 'subscribe', 'tagged_commands', 'tagnum', 'tagpre', 'tagre', 'thread', 'uid', 'unsubscribe', 'untagged_responses', 'welcome', 'xatom']
>>> dir(mail).sort()
>>> d=dir(mail)
>>> d.sort()
>>> d
['PROTOCOL_VERSION', '_CRAM_MD5_AUTH', '__doc__', '__getattr__', '__init__', '__module__', '_append_untagged', '_check_bye', '_checkquote', '_cmd_log', '_cmd_log_idx', '_cmd_log_len', '_command', '_command_complete', '_dump_ur', '_get_line', '_get_response', '_get_tagged_response', '_log', '_match', '_mesg', '_new_tag', '_quote', '_simple_command', '_untagged_response', 'abort', 'append', 'authenticate', 'capabilities', 'capability', 'certfile', 'check', 'close', 'continuation_response', 'copy', 'create', 'debug', 'delete', 'deleteacl', 'error', 'expunge', 'fetch', 'getacl', 'getannotation', 'getquota', 'getquotaroot', 'host', 'is_readonly', 'keyfile', 'list', 'literal', 'login', 'login_cram_md5', 'logout', 'lsub', 'mo', 'mustquote', 'myrights', 'namespace', 'noop', 'open', 'partial', 'port', 'print_log', 'proxyauth', 'read', 'readline', 'readonly', 'recent', 'rename', 'response', 'search', 'select', 'send', 'setacl', 'setannotation', 'setquota', 'shutdown', 'sock', 'socket', 'sort', 'ssl', 'sslobj', 'state', 'status', 'store', 'subscribe', 'tagged_commands', 'tagnum', 'tagpre', 'tagre', 'thread', 'uid', 'unsubscribe', 'untagged_responses', 'welcome', 'xatom']
>>> mail.list()
('OK', ['(\\HasNoChildren) "/" "INBOX"', '(\\HasNoChildren) "/" "Personal"', '(\\HasNoChildren) "/" "Receipts"', '(\\HasNoChildren) "/" "Travel"', '(\\HasNoChildren) "/" "Work"', '(\\Noselect \\HasChildren) "/" "[Gmail]"', '(\\HasNoChildren) "/" "[Gmail]/All Mail"', '(\\HasNoChildren) "/" "[Gmail]/Drafts"', '(\\HasNoChildren) "/" "[Gmail]/Sent Mail"', '(\\HasNoChildren) "/" "[Gmail]/Spam"', '(\\HasNoChildren) "/" "[Gmail]/Starred"', '(\\HasChildren \\HasNoChildren) "/" "[Gmail]/Trash"'])
>>> mail.select("INBOX") # connect to inbox.
('OK', ['3'])
>>> mail.list()
('OK', ['(\\HasNoChildren) "/" "INBOX"', '(\\HasNoChildren) "/" "Personal"', '(\\HasNoChildren) "/" "Receipts"', '(\\HasNoChildren) "/" "Travel"', '(\\HasNoChildren) "/" "Work"', '(\\Noselect \\HasChildren) "/" "[Gmail]"', '(\\HasNoChildren) "/" "[Gmail]/All Mail"', '(\\HasNoChildren) "/" "[Gmail]/Drafts"', '(\\HasNoChildren) "/" "[Gmail]/Sent Mail"', '(\\HasNoChildren) "/" "[Gmail]/Spam"', '(\\HasNoChildren) "/" "[Gmail]/Starred"', '(\\HasChildren \\HasNoChildren) "/" "[Gmail]/Trash"'])
>>> mail.list("INBOX")
('OK', ['(\\HasNoChildren) "/" "INBOX"'])
>>> mail.open("INBOX")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/imaplib.py", line 1149, in open
    self.sock = socket.create_connection((host, port))
  File "/usr/lib/python2.6/socket.py", line 547, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
>>> mail.recent()
('OK', ['0'])
>>> mail.create("sarnoldwashere")
('OK', ['Success'])
>>> mail.list()
('OK', ['(\\HasNoChildren) "/" "INBOX"', '(\\HasNoChildren) "/" "Personal"', '(\\HasNoChildren) "/" "Receipts"', '(\\HasNoChildren) "/" "Travel"', '(\\HasNoChildren) "/" "Work"', '(\\Noselect \\HasChildren) "/" "[Gmail]"', '(\\HasNoChildren) "/" "[Gmail]/All Mail"', '(\\HasNoChildren) "/" "[Gmail]/Drafts"', '(\\HasNoChildren) "/" "[Gmail]/Sent Mail"', '(\\HasNoChildren) "/" "[Gmail]/Spam"', '(\\HasNoChildren) "/" "[Gmail]/Starred"', '(\\HasChildren \\HasNoChildren) "/" "[Gmail]/Trash"', '(\\HasNoChildren) "/" "sarnoldwashere"'])
>>> mail.logout()
('BYE', ['LOGOUT Requested'])
>>> 
...