+ 2
imap_ssl.search one letter name
resp_code, mails = imap_ssl.search(None, '(FROM "a")') I want to search emails from a specific one letter named user, "a". Example: <a@xxxxx.com> <a@xxxxxx.com> Problem is, search results cause all users with an "a" as part of there name to be returned. Example: jane@xxxxx.com aaron@xxxxxx.com Any way to isolate the search to one letter name?
5 Answers
0
The IMAP SEARCH command does not provide an exact match mechanism for the FROM field, meaning it will match any email where "a" appears anywhere in the sender's name or email address. Unfortunately, there is no direct way to force IMAP to only return emails from an exact one-letter sender name.
0
Solution
1. Fetch emails using a broad search.
2. Extract the sender email address using email.message_from_bytes().
3. Use regex or string processing to filter out exact one-letter names.
0
Code Example
import imaplib
import email
import re
# Connect to IMAP server
IMAP_SERVER = "imap.example.com"
EMAIL_ACCOUNT = "your_email@example.com"
PASSWORD = "your_password"
# Login to IMAP
0
imap_ssl = imaplib.IMAP4_SSL(IMAP_SERVER)
imap_ssl.login(EMAIL_ACCOUNT, PASSWORD)
imap_ssl.select("inbox")
# Search for emails broadly
resp_code, mails = imap_ssl.search(None, 'FROM "a"') # Broad search
# Process emails
filtered_emails = []
for num in mails[0].split():
resp_code, data = imap_ssl.fetch(num, "(RFC822)")
msg = email.message_from_bytes(data[0][1])
0
# Extract "From" field
sender = msg["From"]
# Regex to check if sender is exactly "<a@xxxxx.com>"
if re.match(r'^"?\s*a\s*"?\s*<[^@]+@[^>]+>$', sender, re.IGNORECASE):
filtered_emails.append(sender)
# Print filtered results
print(filtered_emails)
# Logout
imap_ssl.logout()