简体   繁体   English

Python IMAP 从或到指定的电子邮件地址搜索

[英]Python IMAP Search from or to designated email address

I am using this with Gmail's SMTP server, and I would like to search via IMAP for emails either sent to or received from an address.我将它与 Gmail 的 SMTP 服务器一起使用,我想通过 IMAP 搜索发送到某个地址或从某个地址接收的电子邮件。

This is what I have:这就是我所拥有的:

mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login('user', 'pass')
mail.list()
mail.select("[Gmail]/All Mail")

status, email_ids = mail.search(None, 'TO "tech163@fusionswift.com" OR FROM "tech163@fusionswift.com"')

The last line of the error is: imaplib.error: SEARCH command error: BAD ['Could not parse command']最后一行报错是: imaplib.error: SEARCH command error: BAD ['Could not parse command']

Not sure how I'm supposed to do that kind of OR statement within python's imaplib .不知道我应该如何在 python 的imaplib执行那种 OR 语句。 If someone can quickly explain what's wrong or point me in the right direction, it'd be greatly appreciated.如果有人能快速解释什么是错的或指出我正确的方向,将不胜感激。

The error you are receiving is generated from the server because it can't parse the search query correctly.您收到的错误是由服务器生成的,因为它无法正确解析搜索查询 In order to generate a valid query follow the RFC 3501 , in page 49 it is explained in detail the structure.为了生成有效的查询,请遵循RFC 3501 ,在第 49 页详细解释了结构。

For example your search string to be correct should be:例如你的搜索字符串是正确的应该是:

'(OR (TO "tech163@fusionswift.com") (FROM "tech163@fusionswift.com"))'

Try to use IMAP query builder from https://github.com/ikvk/imap_tools尝试使用来自https://github.com/ikvk/imap_tools 的IMAP 查询构建器

from imap_tools import A, AND, OR, NOT
# AND
A(text='hello', new=True)  # '(TEXT "hello" NEW)'
# OR
OR(text='hello', date=datetime.date(2000, 3, 15))  # '(OR TEXT "hello" ON 15-Mar-2000)'
# NOT
NOT(text='hello', new=True)  # 'NOT (TEXT "hello" NEW)'
# complex
A(OR(from_='from@ya.ru', text='"the text"'), NOT(OR(A(answered=False), A(new=True))), to='to@ya.ru')

Of course you can use all library tools当然你可以使用所有的库工具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM