【发布时间】:2017-07-26 15:57:40
【问题描述】:
在获取所有“未读”消息然后遍历它们并获取它们之后,我正在尝试操纵单个消息上的 IMAP 标志以将其标记为未读。
我不完全确定如何在单个消息的基础上将消息标记为未读/未见。我得到的只是消息号,我不确定如何正确存储 UID 以仅影响单个消息。
answer in a similar question 似乎不起作用,因为它将 错误 消息设置为“未读”。如何设置我再次获取为“未读”的单个邮件消息?
我被要求提供更多信息。在去掉这里“秘密”的细节的同时,这是我尝试实现的现有运行时,它尝试根据代码规则处理消息,并存储消息编号等,并尝试在将消息的 id 和主题存储在 pickle 文件中后,将每条消息设置为“未读”,因为在运行期间“看到”的任何内容都将在服务器上自动标记为“已读”,而不是设置为“未读”状态:
def main():
conn = imaplib.IMAP4('SERVER')
conn.login('username', 'passphrase')
conn.select('inbox')
(status, nums) = conn.search(None, '(UNSEEN)')
msgnums = map(int, nums[0].split())
for i in msgnums:
try:
raw_msg = conn.fetch(i, '(RFC822)')
raw_msg = conn.fetch(i, '(RFC822)')
msg = email.message_from_string(raw_msg[1][0][1])
body = "Date: %s\r\nSender: %s\r\nSubject: %s\r\n\r\n" % (msg['Date'], msg['From'], msg['Subject'])
msg_date = re.sub('/', '-', msg['Date']).replace(":", ".")
fdate = re.sub('\s+', '_', msg_date).replace(",", "")
print "Checking message: %s" % msg['Subject']
if not msg['Subject']:
continue # fname = "unknown_msg%d_%s" % (i,fdate)
elif msg['Subject'].lower().rfind('foobar') != -1:
print "Subject match 'foobar', processing: %s" % msg['Subject']
# We should have from the pickle an "observed" set of data, both subjects and message numbers.
if msg['Subject'] in PICKLED_MESSAGES['observed']['subjects']:
print "Already handled this message, moving on to next item."
# Since this was already observed we let it be removed so things don't rerun it later.
# noinspection PyBroadException
try:
PICKLED_MESSAGES['observed']['subjects'].remove(msg['Subject'])
PICKLED_MESSAGES['observed']['msgnums'].remove(i)
except:
pass
continue
else:
continue
# Do stuff with the message to store it in a special way on the filesystem
# Note that we've now looked at the message, so next-run we can see
# what was handled on the last run.
PICKLED_MESSAGES['observed']['msgnums'].append(i)
PICKLED_MESSAGES['observed']['subjects'].append(msg['Subject'])
print "PICKLED:\n%s" % PICKLED_MESSAGES['observed']
conn.uid('STORE', str(i), '-FLAGS', '(\Seen)')
except Exception:
conn.uid('STORE', str(i), '-FLAGS', '(\Seen)')
PICKLED_MESSAGES['observed']['msgnums'].remove(i)
PICKLED_MESSAGES['observed']['subjects'].remove(msg['Subject'])
print "PICKLED:\n%s\n" % PICKLED_MESSAGES
finally:
# Store the pickle file so we can use it next run.
cPickle.dump(PICKLED_MESSAGES, open('observed_msgs.pkl', 'wb'))
if __name__ == "__main__":
# pre-runtime checks - is IMAP up, etc. run first, then this:
# Initialize the PICKLED_MESSAGES data with pickle data or an empty
# structure for the pickle.
# noinspection PyBroadException
try:
PICKLED_MESSAGES = cPickle.load(open('observed_msgs.pkl', 'rb'))
except Exception as e:
PICKLED_MESSAGES = {
'observed': {
'msgnums': [],
'subjects': [],
},
}
# If all checks satisfied, continue and process the main() directives.
try:
main()
except Exception as e:
print("CRITICAL An unhandled error has occurred: %s" % str(e))
exit()
但是,不是将正确的消息设置为“未读”;当使用我在系统上看到的建议的方法时。所以,我不完全确定我是否没有正确获取消息的 UID,或者我在这里是否缺少其他东西。
【问题讨论】:
-
如果它在“错误”消息上设置标志,则您必须指定错误的消息 ID。没有任何details on what you're doing and what you're getting,我们不能说别的。
-
@ivan_pozdeev 添加了详细信息,例如代码等,以及我根据邮箱上的 IMAP 检查正在观察发生的内容是否未读已发布.
标签: python python-2.7 email imaplib