IMAP search for email address in the from field

2020-04-21 03:09发布

I am trying to search and filter my imap mails using python's imaplib. I am running into a quite strange problem with the search command, searching for email addresses in the FROM field. I have the following script,

print('search with name')
status, results = con.search(None, '(FROM "Shrikant Sharat")')
if status == 'OK':
    if results[0]:
        mid = results[0].split()[0]
        print('mail id', mid)
        print(con.fetch(mid, '(UID BODY[HEADER.FIELDS (FROM)])'))
    else:
        print('No results yielded')
else:
    print('unable to search', results)

print()
print('search with email')
status, results = con.search(None, '(FROM "shrikantsharat.k@gmail.com")')
if status == 'OK':
    if results[0]:
        mid = results[0].split()[0]
        print('mail id', mid)
        print(con.fetch(mid, '(UID BODY[HEADER.FIELDS (FROM)])'))
    else:
        print('No results yielded')
else:
    print('unable to search', results)

for which, I get the following result,

search with name
mail id 2155
('OK', [('2155 (UID 5340 BODY[HEADER.FIELDS (FROM)] {54}', 'From: Shrikant Sharat <shrikantsharat.k@gmail.com>\r\n\r\n'), ' FLAGS (\\Seen))'])

search with email
No results yielded

Why does the second search fail? The email address is present in the From field as shown by the previous search. The second search should've matched this mail right?

Is this not the way to search for email address in the From field? I am pulling my hair apart on this one. Any ideas?

Edit If relevant, I am trying this with an IMAP server exposed by MS Exchange (2007, I think).

1条回答
祖国的老花朵
2楼-- · 2020-04-21 03:10

use this as your filter:

(HEADER FROM "shrikantsharat.k@gmail.com")
查看更多
登录 后发表回答