0

我在 python 中编写了一个电子邮件解析机制。

它会找到一封新电子邮件并正确传递数据。我 99.999% 确定我的代码运行正常,所以那里应该没有问题。问题是有时,Gmail 收件箱会被视为“看不见”的邮件淹没。在这一点上,我的代码无能为力。

它失败了:

imaplib.error: FETCH 命令错误: BAD ['Could not parse command']

这很令人痛苦,我很想拥有

  1. 一种检查看不见的消息是否已溢出到此状态的方法,或者
  2. 一种手动(通过 imaplib)将所有消息标记为已读的方法,包括检测此特定错误的方法。

关于如何做到这一点的任何想法?

这是我的代码:

#!/usr/bin/env python

import imaplib, re, sys, time, OSC, threading, os

iparg = 'localhost' 
oportarg = 9000
iportarg = 9002
usern = 'myusrname@gmail.com'
gpass = 'mypass' 
kill_program = False

server = imaplib.IMAP4_SSL('imap.googlemail.com', 993)
oclient = OSC.OSCClient()
email_interval = 2.0

def login():
    server.login(usern, gpass)
    oclient.connect((iparg, oportarg))

def logout_handle(addr, tags, stuff, source):
    print 'received kill call'
    global kill_program
    kill_program = True

def filter_signature(s):  #so annoying; wish i didn't have to do this
    try:
    a_sig = re.sub(r'Sent|--Sent', '', s)
    b_sig = re.sub(r'using SMS-to-email.  Reply to this email to text the sender back and', '', a_sig)
    c_sig = re.sub(r'save on SMS fees.', '', b_sig)
    d_sig = re.sub(r'https://www.google.com/voice', '', c_sig)
    no_lines = re.sub(r'\n|=|\r?', '', d_sig) #add weird characters to this as needed
    except:
    nolines = s
    return no_lines

def parse_email(interval):
    while True:
    server.select('INBOX')
    status, ids = server.search(None, 'UnSeen')
    print 'status is: ', status

    if not ids or ids[0] is '':
        print 'no new messages'
    else:
        try:
        print 'found a message; attempting to parse...'
        latest_id = ids[0]
        status, msg_data = server.fetch(latest_id, '(UID BODY[TEXT])')
        raw_data = msg_data[0][1]
        raw_filter = raw_data

        print 'message result: ', raw_filter
    time.sleep(interval)

#execute main block
while not kill_program:
    login()
    parse_email(email_interval)

st.kill()
sys.exit()
4

1 回答 1

1

根据错误,我会非常仔细地检查您传递给 fetch 的参数。Gmail 告诉您它无法解析您发送给它的命令。

此外,您可以执行 STORE +FLAGS \SEEN 将消息标记为已读。

于 2013-02-07T18:01:14.813 回答