我正在尝试创建一个应用程序来检索和分析通过gmail发送的电子邮件。我正在使用此处的教程进行更改; http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
readmail.py
EMAIL_ACCOUNT = "*****"
PASSWD = "*****"
def process_mailbox(M):
rv, data = M.search(None, "ALL")
resp, items = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data, = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return
msg = email.message_from_bytes(data[0][1])
hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
if msg.is_multipart():
for part in msg.get_payload():
body = part.get_payload()
subject = str(hdr)
print('Message %s: %s' % (num, subject))
print('Body:', body)
M = imaplib.IMAP4_SSL('imap.gmail.com',993)
try:
rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
print ("LOGIN FAILED!!! ")
sys.exit(1)
print(rv, data)
rv, data = M.select("INBOX")
if rv == 'OK':
print("Processing mailbox...\n")
process_mailbox(M)
M.close()
else:
print("ERROR: Unable to open mailbox ", rv)
M.logout()
当我通过命令行运行此代码时,输出是预期的,但是当通过基本的烧瓶导入时,整个事情就会崩溃。
app.py
from flask import Flask, render_template, jsonify, request
from readmail import process_mailbox
import json
import imaplib
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template('index.html')
@app.route('/test')
def test():
return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
if __name__ == '__main__':
app.run(use_reloader=True, debug=True)
我收到的错误是;
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1612, in
full_dispatch_request
rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\project\flask\venv\Project\app.py", line 13, in test
return json.dumps({'name':
process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
File "C:\Users\user\project\flask\venv\Project\readmail.py", line 14, in process_mailbox
M.select('"[Gmail]/All Mail"')
File "C:\Python34\lib\imaplib.py", line 683, in select
typ, dat = self._simple_command(name, mailbox)
File "C:\Python34\lib\imaplib.py", line 1134, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python34\lib\imaplib.py", line 882, in _command
', '.join(Commands[name])))imaplib.error: command SELECT illegal in state NONAUTH, only allowed in
states AUTH, SELECTED
上周我曾多次尝试找出解决此错误的方法,以便获得任何帮助。
答案 0 :(得分:1)
首先,看一下追溯的结尾,你已经获得了imaplib.error: command SELECT illegal in state NONAUTH, only allowed in states AUTH, SELECTED
- 然后回到代码的追溯中的两行:
app.py, test ... return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
readmail.py process_mailbox ... M.select('"[Gmail]/All Mail"')
我已经在这里修剪了一些,但在测试中,您只是连接到Gmail IMAP服务器,但没有登录。以下代码是您的第一个文件所做的:
M = imaplib.IMAP4_SSL('imap.gmail.com',993)
try:
rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
print ("LOGIN FAILED!!! ")
sys.exit(1)
此外,process_mailbox
只会返回null,它会更改您直接传递的对象。