gpt4 book ai didi

Python:Gmail 未读邮件崩溃

转载 作者:太空狗 更新时间:2023-10-30 01:47:02 24 4
gpt4 key购买 nike

import imaplib, re
import os
import time
import socket

imap_host = 'imap.gmail.com'
mail = imaplib.IMAP4_SSL(imap_host)
mail.login("xxx@example.com", "sddd")

while True:
try:
print 'Connecting to Inbox..'
mail.select("inbox") # connect to inbox.
result, data = mail.uid('search', None, 'UNSEEN')
uid_list = data[0].split()
print len(uid_list), 'Unseen emails.'
if len(uid_list) > 20:
os.system('heroku restart --app xx-xx-203')
time.sleep(30)
except:
print 'Error'
imap_host = 'imap.gmail.com'
mail = imaplib.IMAP4_SSL(imap_host)
mail.login("xxx@example.com", "xxx")
pass

完美运行,但有时会崩溃:

Restarting processes... done
Connecting to Inbox..
Error
Traceback (most recent call last):
File "gmail_new9.py", line 24, in <module>
mail.login("xxx@ccc.com", "ddddd")
File "/usr/lib/python2.6/imaplib.py", line 498, in login
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
File "/usr/lib/python2.6/imaplib.py", line 1060, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.6/imaplib.py", line 893, in _command_complete
self._check_bye()
File "/usr/lib/python2.6/imaplib.py", line 808, in _check_bye
raise self.abort(bye[-1])
imaplib.abort: [UNAVAILABLE] Temporary System Error

我该如何解决这个问题?

最佳答案

您的脚本崩溃的原因是在“except” block 内调用 mail.login() 引发了一个从未被捕获的异常。

imaplib 的文档指出,当您遇到 imaplib.abort 异常时,您应该重试您的命令。

http://docs.python.org/library/imaplib

exception IMAP4.abort IMAP4 server errors cause this exception to be raised. This is a sub-class of IMAP4.error. Note that closing the instance and instantiating a new one will usually allow recovery from this exception.

还有

>>> help('imaplib')

同样的说:

"abort" exceptions imply the connection should be reset, and the command re-tried.

修复方法如下:

import imaplib, re
import os
import time
import socket

def connect(retries=5, delay=3):
while True:
try:
imap_host = 'imap.gmail.com'
mail = imaplib.IMAP4_SSL(imap_host)
mail.login("xxx@example.com", "sddd")
return mail
except imaplib.IMAP4_SSL.abort:
if retries > 0:
retries -= 1
time.sleep(delay)
else:
raise

mail = connect()
while True:
try:
print 'Connecting to Inbox..'
mail.select("inbox") # connect to inbox.
result, data = mail.uid('search', None, 'UNSEEN')
uid_list = data[0].split()
print len(uid_list), 'Unseen emails.'
if len(uid_list) > 20:
os.system('heroku restart --app xx-xx-203')
time.sleep(30)
except:
print 'Error'
mail = connect()

关于Python:Gmail 未读邮件崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com