Skip to content

Query

email_profile.clients.imap.query.Query

Bases: BaseModel

IMAP search query builder.

Use kwargs for simple queries::

Query(subject="hello", unseen=True)

Use Query.where for composable expressions::

Query.where.subject("hello") & Query.where.unseen()

Chain with .exclude() and .or_()::

Query(subject="report").exclude(from_="spam").or_(subject="urgent")
Source code in email_profile/clients/imap/query.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class Query(BaseModel):
    """IMAP search query builder.

    Use kwargs for simple queries::

        Query(subject="hello", unseen=True)

    Use ``Query.where`` for composable expressions::

        Query.where.subject("hello") & Query.where.unseen()

    Chain with ``.exclude()`` and ``.or_()``::

        Query(subject="report").exclude(from_="spam").or_(subject="urgent")
    """

    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    since: Optional[date] = None
    before: Optional[date] = None
    on: Optional[date] = None
    sent_since: Optional[date] = None
    sent_before: Optional[date] = None

    subject: Optional[str] = None
    from_who: Optional[str] = Field(default=None, alias="from")
    to: Optional[str] = None
    cc: Optional[str] = None
    bcc: Optional[str] = None

    body: Optional[str] = None
    text: Optional[str] = None
    keyword: Optional[str] = None

    larger: Optional[int] = None
    smaller: Optional[int] = None

    seen: Optional[bool] = None
    answered: Optional[bool] = None
    flagged: Optional[bool] = None
    deleted: Optional[bool] = None
    draft: Optional[bool] = None

    unseen: Optional[bool] = None

    def _date_clauses(self) -> list[str]:
        fields = (
            ("SINCE", self.since),
            ("BEFORE", self.before),
            ("ON", self.on),
            ("SENTSINCE", self.sent_since),
            ("SENTBEFORE", self.sent_before),
        )
        return [
            f"({name} {_imap_date(value)})" for name, value in fields if value
        ]

    def _string_clauses(self) -> list[str]:
        fields = (
            ("SUBJECT", self.subject),
            ("FROM", self.from_who),
            ("TO", self.to),
            ("CC", self.cc),
            ("BCC", self.bcc),
            ("BODY", self.body),
            ("TEXT", self.text),
            ("KEYWORD", self.keyword),
        )
        return [
            f'({name} "{_ascii(value)}")' for name, value in fields if value
        ]

    def _size_clauses(self) -> list[str]:
        fields = (("LARGER", self.larger), ("SMALLER", self.smaller))
        return [
            f"({name} {value})" for name, value in fields if value is not None
        ]

    @model_validator(mode="after")
    def _check_seen_unseen(self) -> Query:
        if self.seen is True and self.unseen is True:
            raise ValueError("Cannot set both seen=True and unseen=True.")
        return self

    def _flag_clauses(self) -> list[str]:
        fields = (
            (self.seen, "SEEN"),
            (self.answered, "ANSWERED"),
            (self.flagged, "FLAGGED"),
            (self.deleted, "DELETED"),
            (self.draft, "DRAFT"),
        )
        parts: list[str] = []
        for flag, name in fields:
            if flag is True:
                parts.append(f"({name})")
        if self.unseen is True:
            parts.append("(UNSEEN)")
        return parts

    def _clauses(self) -> list[str]:
        return (
            self._date_clauses()
            + self._string_clauses()
            + self._size_clauses()
            + self._flag_clauses()
        )

    def mount(self) -> str:
        parts = self._clauses()
        return " ".join(parts) if parts else "ALL"

    def exclude(self, **kwargs: object) -> _Expr:
        return _Expr(self.mount()) & ~_Expr(Query(**kwargs).mount())

    def or_(self, **kwargs: object) -> _Expr:
        return _Expr(self.mount()) | _Expr(Query(**kwargs).mount())

    def __and__(self, other: QueryLike) -> _Expr:
        return _Expr(self.mount()) & _to_expr(other)

    def __or__(self, other: QueryLike) -> _Expr:
        return _Expr(self.mount()) | _to_expr(other)

    def __invert__(self) -> _Expr:
        return ~_Expr(self.mount())

answered = None class-attribute instance-attribute

bcc = None class-attribute instance-attribute

before = None class-attribute instance-attribute

body = None class-attribute instance-attribute

cc = None class-attribute instance-attribute

deleted = None class-attribute instance-attribute

draft = None class-attribute instance-attribute

flagged = None class-attribute instance-attribute

from_who = Field(default=None, alias='from') class-attribute instance-attribute

keyword = None class-attribute instance-attribute

larger = None class-attribute instance-attribute

model_config = ConfigDict(extra='forbid', populate_by_name=True) class-attribute instance-attribute

on = None class-attribute instance-attribute

seen = None class-attribute instance-attribute

sent_before = None class-attribute instance-attribute

sent_since = None class-attribute instance-attribute

since = None class-attribute instance-attribute

smaller = None class-attribute instance-attribute

subject = None class-attribute instance-attribute

text = None class-attribute instance-attribute

to = None class-attribute instance-attribute

unseen = None class-attribute instance-attribute

__and__(other)

Source code in email_profile/clients/imap/query.py
306
307
def __and__(self, other: QueryLike) -> _Expr:
    return _Expr(self.mount()) & _to_expr(other)

__invert__()

Source code in email_profile/clients/imap/query.py
312
313
def __invert__(self) -> _Expr:
    return ~_Expr(self.mount())

__or__(other)

Source code in email_profile/clients/imap/query.py
309
310
def __or__(self, other: QueryLike) -> _Expr:
    return _Expr(self.mount()) | _to_expr(other)

exclude(**kwargs)

Source code in email_profile/clients/imap/query.py
300
301
def exclude(self, **kwargs: object) -> _Expr:
    return _Expr(self.mount()) & ~_Expr(Query(**kwargs).mount())

mount()

Source code in email_profile/clients/imap/query.py
296
297
298
def mount(self) -> str:
    parts = self._clauses()
    return " ".join(parts) if parts else "ALL"

or_(**kwargs)

Source code in email_profile/clients/imap/query.py
303
304
def or_(self, **kwargs: object) -> _Expr:
    return _Expr(self.mount()) | _Expr(Query(**kwargs).mount())