Using email attributes and filters
As shown earlier in the Getting Started section, we can use different attributes in a filter when retrieving some emails.
The search method
A way to search for emails using filters is through the search
method, in this case a complete string referring to the criterion to be used must be passed. This way makes it the user's responsibility to use the attributes and syntax correctly.
...
# Searches for all emails sending by the address: joao@email.com
messages = email.search('FROM "joao@email.com"')
...
The filter_by method
In some cases, the way above can get a little confusing or generate doubts when building the filter string. Therefore, it is possible to use the filter_by
method as a "shortcut" to make the filters.
from botcity.plugins.email import MailFilters
from datetime import datetime
...
# You can view and select an attribute using: MailFilters.<ATTRIBUTE_NAME>
# Searches for all emails sending by the address: joao@email.com
messages = email.filter_by(MailFilters.FROM, "joao@email.com")
# Searches for all emails that have not yet been read
messages = email.filter_by(MailFilters.SEEN, False)
# Searches for all emails that were received on the date: 15/02/2022
messages = email.filter_by(MailFilters.ON_DATE, datetime(2022, 2, 15).date())
...
In this case, it is not necessary to worry about the syntax of the filter string, just pass the desired attribute in the filter and the value that this attribute should have.
The attributes that can be used are defined in the MailFilters
class as a Enum, the following table shows the attributes that are defined and what types of values they can receive:
Attribute | Description | Type of value |
---|---|---|
SEEN |
with/without the Seen flag | bool |
FROM |
address from email sender | str |
TO |
address receiver as TO | str |
CC |
address receiver as CC | str |
BCC |
address receiver as BCC | str |
SUBJECT |
the email subject | str |
TEXT_CONTENT |
contains the text in the email body | str |
ON_DATE |
email date is within specified date | datetime.date |
DATE_GREATER_THAN |
email date is within or later than the specified date | datetime.date |
DATE_LESS_THAN |
email date is earlier than the specified date | datetime.date |