I'm using imap library to search in a gmail account however I want to do it taking into account some labels I have over the mails and if they have attachments or not. There is an insane amount of emails so it's not possible to check individually for this conditions in the mails is has to be done with the search() command however I've been trying some approaches with no success.
Here is my code:
import imaplib
import email
from email.header import decode_header
from email.utils import parsedate_to_datetime
from datetime import datetime, timedelta
# Informacion del servidor
mail_server = "imap.gmail.com"
mail_port = 993
# Conectarse al servidor
try:
mail = imaplib.IMAP4_SSL(mail_server)
except imaplib.IMAP4.error as e:
print(f"Failed to connect to the mail server: {e}")
exit(1)
# Conectarse a la cuenta
try:
mail.login(email_address, app_password)
except imaplib.IMAP4.error as e:
print(f"Login failed: {e}")
exit(1)
# Seleccionar el lugar donde se encuentran los correos
mail.select("INBOX")
date_threshold = datetime.now() - timedelta(hours=2)
# status, messages = mail.search(None, '(SINCE {date})'.format(date=date_threshold.strftime('%d-%b-%Y')))
# status, messages = mail.search(None, 'UNKEYED (NOT LABEL "CustomLabel") (SINCE {date})'.format(date=date_threshold.strftime('%d-%b-%Y')))
status, messages = mail.search(None, 'HASATTACH (SINCE {date})'.format(date=date_threshold.strftime('%d-%b-%Y')))
message_ids = messages[0].split()
I appreciate the help!