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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
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
272
273
def __and__(self, other: QueryLike) -> _Expr:
    return _Expr(self.mount()) & _to_expr(other)

__invert__()

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

__or__(other)

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

exclude(**kwargs)

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

mount()

Source code in email_profile/clients/imap/query.py
262
263
264
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
269
270
def or_(self, **kwargs: object) -> _Expr:
    return _Expr(self.mount()) | _Expr(Query(**kwargs).mount())