pymap.parsing

Package defining all the IMAP parsing and response classes.

class pymap.parsing.ParsedT

Type variable used for specifying the data parsed by a Parseable sub-class.

alias of TypeVar(‘ParsedT’)

pymap.parsing.AnyParseable: TypeAlias = 'Parseable[Any]'

Type alias for an unspecified parseable object.

class pymap.parsing.ParseableT

Type variable used for parseable objects.

alias of TypeVar(‘ParseableT’, bound=AnyParseable)

pymap.parsing.AnyParseableType: TypeAlias = 'ParseableType[Any]'

Type alias for an unspecified parseable type.

class pymap.parsing.Params(state=None, *, expected=None, list_limit=None, command_name=None, uid=False, charset=None, tag=None, max_append_len=None, allow_continuations=True)[source]

Parameters used and passed around among the parse() methods.

Parameters:
  • state (ParsingState | None) – The mutable parsing state.

  • expected (Sequence[AnyParseableType] | None) – The types that are expected to be parsed..

  • list_limit (int | None) – The maximum number of items in a parsed list.

  • command_name (bytes | None) – The name of the command currently being parsed, if any.

  • uid (bool) – The next parsed command came after a UID command.

  • charset (str | None) – Strings should be decoded using this character set.

  • tag (bytes | None) – The next parsed command uses this tag bytestring.

  • max_append_len (int | None) – The maximum allowed length of the message body to an APPEND command.

  • allow_continuations (bool) – Allow literal strings that require continuation data.

copy(state=None, *, expected=None, list_limit=None, command_name=None, uid=None, charset=None, tag=None, max_append_len=None, allow_continuations=None)[source]

Copy the parameters, possibly replacing a subset.

Parameters:
  • state (ParsingState | None) –

  • expected (Sequence[ParseableType[Any]] | None) –

  • list_limit (int | None) –

  • command_name (bytes | None) –

  • uid (bool | None) –

  • charset (str | None) –

  • tag (bytes | None) –

  • max_append_len (int | None) –

  • allow_continuations (bool | None) –

Return type:

Params

class pymap.parsing.Parseable[source]

Represents a parseable data object from an IMAP stream. The sub-classes implement the different data formats.

This base class will be inherited by all necessary entries in the IMAP formal syntax section.

abstract property value: ParsedT

The primary value associated with the parsed data.

abstract classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Parseable[ParsedT], memoryview]

class pymap.parsing.ExpectedParseable[source]

Non-instantiable class, used to parse a buffer from a list of expected types.

classmethod parse(buf, params)[source]

Parses the given buffer by attempting to parse the list of expected types until one of them succeeds, then returns the parsed object.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Parseable[Any], memoryview]

class pymap.parsing.Space(length)[source]

Represents at least one space character.

Parameters:

length (int) – The number of spaces parsed.

property value: int

The number of spaces parsed.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Space, memoryview]

class pymap.parsing.EndLine(preceding_spaces=0, carriage_return=True)[source]

Represents the end of a parsed line. This will only parse if the buffer has zero or more space characters followed by a new-line sequence.

Parameters:
  • preceding_spaces (int) – The number of space characteres before the newline.

  • carriage_return (bool) – Whether the newline included a carriage return.

preceding_spaces

The number of space characteres before the newline.

carriage_return

Whether the newline included a carriage return.

property value: bytes

The endline bytestring.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[EndLine, memoryview]

pymap.parsing.exceptions

exception pymap.parsing.exceptions.NotParseable(buf, code=None)[source]

Indicates that the given buffer was not parseable by one or all of the data formats.

Parameters:
  • buf (memoryview) – The buffer with the parsing error.

  • code (MaybeBytes | None) –

Return type:

None

exception pymap.parsing.exceptions.InvalidContent(buf, code=None)[source]

Indicates the type of the parsed content was correct, but something about the content did not fit what was expected by the special type.

Parameters:
  • buf (memoryview) –

  • code (MaybeBytes | None) –

Return type:

None

exception pymap.parsing.exceptions.UnexpectedType(buf, code=None)[source]

Indicates that a generic parseable that was given a sub-type expectation failed to meet that expectation.

Parameters:
  • buf (memoryview) –

  • code (MaybeBytes | None) –

Return type:

None

pymap.parsing.state

class pymap.parsing.state.ParsingExpectedT

Type variable for expected data during parsing.

alias of TypeVar(‘ParsingExpectedT’)

class pymap.parsing.state.ParsingState(*, continuations=())[source]

Contains mutable parsing state. As parsing advances, it may need external data to proceed. Because parsing is linear, these expectations are defined as sequence of objects that are iterated during parsing.

Warning

The expectation keys and object types are dynamic, to prevent cyclic dependencies in the parsing system.

See also

pymap.parsing.interrupts.ParsingInterrupt

Parameters:

continuations (Sequence[memoryview]) – The IMAP literal string continuations.

exception pymap.parsing.state.ParsingInterrupt(expected)[source]

Exception thrown to interrupt the IMAP parsing process, because an expectation was not met. The caller should update provide an updated ParsingState object that meets the expectation.

Parameters:

expected (ParsingExpectation[Any]) – The required data expectation.

Return type:

None

class pymap.parsing.state.ParsingExpectation[source]

Base class for parsing expectations that may require additional data before parsing can advance.

abstract consume(state)[source]

Consume and return a piece of data, if available.

Parameters:

state (ParsingState) – The parsing state.

Return type:

ParsingExpectedT | None

expect(state)[source]

Indicates that the buffer has been successfully parsed so far, but additional data is expected from the parsing state.

Parameters:

state (ParsingState) – The parsing state object.

Raises:

ParsingInterrupt – The expected data was not available.

Return type:

ParsingExpectedT

pymap.parsing.commands

pymap.parsing.commands.builtin_commands: Collection[type[Command]] = [<class 'pymap.parsing.command.any.CapabilityCommand'>, <class 'pymap.parsing.command.any.LogoutCommand'>, <class 'pymap.parsing.command.any.NoOpCommand'>, <class 'pymap.parsing.command.any.IdCommand'>, <class 'pymap.parsing.command.auth.AppendCommand'>, <class 'pymap.parsing.command.auth.CreateCommand'>, <class 'pymap.parsing.command.auth.DeleteCommand'>, <class 'pymap.parsing.command.auth.ExamineCommand'>, <class 'pymap.parsing.command.auth.ListCommand'>, <class 'pymap.parsing.command.auth.LSubCommand'>, <class 'pymap.parsing.command.auth.RenameCommand'>, <class 'pymap.parsing.command.auth.SelectCommand'>, <class 'pymap.parsing.command.auth.StatusCommand'>, <class 'pymap.parsing.command.auth.SubscribeCommand'>, <class 'pymap.parsing.command.auth.UnsubscribeCommand'>, <class 'pymap.parsing.command.nonauth.AuthenticateCommand'>, <class 'pymap.parsing.command.nonauth.LoginCommand'>, <class 'pymap.parsing.command.nonauth.StartTLSCommand'>, <class 'pymap.parsing.command.select.CheckCommand'>, <class 'pymap.parsing.command.select.CloseCommand'>, <class 'pymap.parsing.command.select.ExpungeCommand'>, <class 'pymap.parsing.command.select.CopyCommand'>, <class 'pymap.parsing.command.select.MoveCommand'>, <class 'pymap.parsing.command.select.FetchCommand'>, <class 'pymap.parsing.command.select.StoreCommand'>, <class 'pymap.parsing.command.select.SearchCommand'>, <class 'pymap.parsing.command.select.UidCommand'>, <class 'pymap.parsing.command.select.UidCopyCommand'>, <class 'pymap.parsing.command.select.UidMoveCommand'>, <class 'pymap.parsing.command.select.UidExpungeCommand'>, <class 'pymap.parsing.command.select.UidFetchCommand'>, <class 'pymap.parsing.command.select.UidSearchCommand'>, <class 'pymap.parsing.command.select.UidStoreCommand'>, <class 'pymap.parsing.command.select.IdleCommand'>]

List of built-in commands. These commands are automatically registered by a new Commands object.

class pymap.parsing.commands.InvalidCommand(params, parse_exc, command=None, command_type=None)[source]

An invalid command, either because the tag or command name could not be parsed, the command name was not recognized, or a known command was given invalid arguments.

Parameters:
  • params (Params) – The parsing parameters

  • parse_exc (NotParseable | None) – The exception that caused the failure, if any.

  • command (ClassVar[bytes]) – The command name, if available.

  • command_type (type[Command] | None) – The command type, if available.

command: ClassVar[bytes] = b'[INVALID]'

The command key, e.g. b'NOOP'.

property value: bytes

The command name.

property message: bytes

The message to include in a BAD response.

property command_name: bytes | None

The command name, if the name could be parsed.

property command_type: type[Command] | None

The command type, if parsing failed due to invalid arguments.

property parse_exc: NotParseable | None

The parsing exception, if any.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[InvalidCommand, memoryview]

class pymap.parsing.commands.Commands[source]

Manages the set of all known IMAP commands and the ability to parse.

register(cmd)[source]

Register a new IMAP command.

Parameters:

cmd (type[Command]) – The new command type.

Return type:

None

deregister(name)[source]

Deregister an IMAP command by name. Does nothing if the command is not registered.

Parameters:

name (bytes) – The IMAP command name.

Return type:

None

parse(buf, params)[source]

Parse the given bytes into a command. The basic syntax is a tag string, a command name, possibly some arguments, and then an endline. If the command has a complete structure but cannot be parsed, an InvalidCommand is returned.

Parameters:
  • buf (memoryview) – The bytes to parse.

  • params (Params) – The parsing parameters.

Return type:

tuple[Command, memoryview]

pymap.parsing.command

class pymap.parsing.command.Command(tag)[source]

Base class to represent the commands available to clients.

Parameters:

tag (bytes) – The tag parsed from the beginning of the command line.

command: ClassVar[bytes] = b''

The command key, e.g. b'NOOP'.

delegate: ClassVar[type[Command] | None] = None

If given, execution of this command is handled by the delegate command.

compound: ClassVar[bool] = False

True if the command is part of a compound command.

tag

The tag parsed from the beginning of the command line.

property value: bytes

The command name.

abstract classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Command, memoryview]

class pymap.parsing.command.CommandNoArgs(tag)[source]

Convenience class used to fail parsing when args are given to a command that expects nothing.

Parameters:

tag (bytes) –

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[CommandNoArgs, memoryview]

class pymap.parsing.command.CommandAny(tag)[source]

Represents a command available at any stage of the IMAP session.

Parameters:

tag (bytes) –

class pymap.parsing.command.CommandAuth(tag)[source]

Represents a command available when the IMAP session has been authenticated.

Parameters:

tag (bytes) –

class pymap.parsing.command.CommandNonAuth(tag)[source]

Represents a command available only when the IMAP session has not yet authenticated.

Parameters:

tag (bytes) –

class pymap.parsing.command.CommandSelect(tag)[source]

Represents a command available only when the IMAP session has been authenticated and a mailbox has been selected.

Parameters:

tag (bytes) –

class pymap.parsing.command.any.CapabilityCommand(tag)[source]

The CAPABILITY command lists current server capabilities.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'CAPABILITY'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.any.LogoutCommand(tag)[source]

The LOGOUT command ends the IMAP session.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'LOGOUT'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.any.NoOpCommand(tag)[source]

The NOOP command does nothing, but can be used to check for state changes on a selected mailbox.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'NOOP'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.any.IdCommand(tag, parameters)[source]

The ID command allows the client and server to provide each other information for statistical purposes and bug reporting.

See also

RFC 2971

Parameters:
  • tag (bytes) – The command tag.

  • parameters (Mapping[bytes, bytes] | None) – A mapping of the keys and values provided by the client.

command: ClassVar[bytes] = b'ID'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[IdCommand, memoryview]

class pymap.parsing.command.nonauth.AuthenticateCommand(tag, mech_name)[source]

The AUTHENTICATE command authenticates an IMAP session using a SASL mechanism.

Parameters:
  • tag (bytes) – The command tag.

  • mech_name (bytes) – The SASL mechanism name.

command: ClassVar[bytes] = b'AUTHENTICATE'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[AuthenticateCommand, memoryview]

class pymap.parsing.command.nonauth.LoginCommand(tag, userid, password)[source]

The LOGIN command authenticates an IMAP session using a basic user ID and password credentials in clear-text.

Parameters:
  • tag (bytes) – The command tag.

  • userid (bytes) – The user ID bytestring.

  • password (bytes) – The password bytestring.

command: ClassVar[bytes] = b'LOGIN'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[LoginCommand, memoryview]

class pymap.parsing.command.nonauth.StartTLSCommand(tag)[source]

The STARTTLS command attempts to encrypt a non-encrypted IMAP session using opportunistic TLS. The client/server handshake should take place immediately after the server issues a ResponseOk.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'STARTTLS'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.auth.AppendCommand(tag, mailbox, messages, cancelled=False, error=None)[source]

The APPEND command adds a new message to a mailbox.

See also

RFC 3502 6.3.11.

Parameters:
  • tag (bytes) – The command tag.

  • mailbox (Mailbox) – The mailbox name.

  • messages (Iterable[AppendMessage]) – List of tuples containing the raw messages bytes, the flags, and the internal timestamp to assign to the message.

  • cancelled (bool) – True if the append command was cancelled.

  • error (Exception | None) –

command: ClassVar[bytes] = b'APPEND'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[AppendCommand, memoryview]

class pymap.parsing.command.auth.CreateCommand(tag, mailbox, options)[source]

The CREATE command creates a new mailbox.

Parameters:
command: ClassVar[bytes] = b'CREATE'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[CreateCommand, memoryview]

class pymap.parsing.command.auth.DeleteCommand(tag, mailbox)[source]

The DELETE command deletes a mailbox.

Parameters:
command: ClassVar[bytes] = b'DELETE'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.auth.ExamineCommand(tag, mailbox, options)[source]

The EXAMINE command selects a mailbox as read-only for querying and state changes.

Parameters:
command: ClassVar[bytes] = b'EXAMINE'

The command key, e.g. b'NOOP'.

delegate

alias of SelectCommand

readonly: ClassVar[bool] = True

The mailbox will be opened read-only.

class pymap.parsing.command.auth.ListCommand(tag, ref_name, filter_)[source]

The LIST command lists existing mailboxes.

Parameters:
  • tag (bytes) – The command tag.

  • ref_name (str) – The mailbox reference name.

  • filter – The mailbox filter string.

  • filter_ (str) –

command: ClassVar[bytes] = b'LIST'

The command key, e.g. b'NOOP'.

only_subscribed: ClassVar[bool] = False

All mailboxes may be listed, not only subscribed mailboxes.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[ListCommand, memoryview]

class pymap.parsing.command.auth.LSubCommand(tag, ref_name, filter_)[source]

The LSUB command lists subscribed mailboxes.

Parameters:
command: ClassVar[bytes] = b'LSUB'

The command key, e.g. b'NOOP'.

delegate

alias of ListCommand

only_subscribed: ClassVar[bool] = True

Only subscribed mailboxes may be listed.

class pymap.parsing.command.auth.RenameCommand(tag, from_mailbox, to_mailbox, options)[source]

The RENAME command renames an existing mailbox.

Parameters:
command: ClassVar[bytes] = b'RENAME'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[RenameCommand, memoryview]

class pymap.parsing.command.auth.SelectCommand(tag, mailbox, options)[source]

The SELECT command selects a mailbox for querying, updates, and state changes.

Parameters:
command: ClassVar[bytes] = b'SELECT'

The command key, e.g. b'NOOP'.

readonly: ClassVar[bool] = False

The mailbox will not be opened read-only unless the backend indicates that it must be.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[SelectCommand, memoryview]

class pymap.parsing.command.auth.StatusCommand(tag, mailbox, status_list)[source]

The STATUS command returns information about a mailbox without selecting it.

Parameters:
  • tag (bytes) – The command tag.

  • mailbox (Mailbox) – The mailbox name.

  • status_list (Sequence[StatusAttribute]) – The status attributes to return.

command: ClassVar[bytes] = b'STATUS'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[StatusCommand, memoryview]

class pymap.parsing.command.auth.SubscribeCommand(tag, mailbox)[source]

The SUBSCRIBE command subscribes to an existing mailbox.

Parameters:
command: ClassVar[bytes] = b'SUBSCRIBE'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.auth.UnsubscribeCommand(tag, mailbox)[source]

The UNSUBSCRIBE command unsubscribes from a subscribed mailbox.

Parameters:
command: ClassVar[bytes] = b'UNSUBSCRIBE'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.select.CheckCommand(tag)[source]

The CHECK command initiates an implementation-specific backend synchronization for the selected mailbox.

See also

RFC 3501 6.4.1.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'CHECK'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.select.CloseCommand(tag)[source]

The CLOSE command closes a selected mailbox.

See also

RFC 3501 6.4.2.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'CLOSE'

The command key, e.g. b'NOOP'.

class pymap.parsing.command.select.ExpungeCommand(tag, uid_set=None)[source]

The EXPUNGE command permanently erases all messages in the selected mailbox that contain the \Deleted flag.

Parameters:
  • tag (bytes) – The command tag.

  • uid_set (SequenceSet | None) – Only the messages in the given UID set should be expunged.

command: ClassVar[bytes] = b'EXPUNGE'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[ExpungeCommand, memoryview]

class pymap.parsing.command.select.CopyCommand(tag, seq_set, mailbox)[source]

The COPY command copies messages from the selected mailbox to the end of the destination mailbox.

See also

RFC 3501 6.4.7.

Parameters:
  • tag (bytes) – The command tag.

  • seq_set (SequenceSet) – The sequence set of the messages to copy.

  • mailbox (Mailbox) – The destination mailbox.

command: ClassVar[bytes] = b'COPY'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[CopyCommand, memoryview]

class pymap.parsing.command.select.MoveCommand(tag, seq_set, mailbox)[source]

The MOVE command moves messages from the selected mailbox to the end of the destination mailbox.

See also

RFC 6851

Parameters:
  • tag (bytes) – The command tag.

  • seq_set (SequenceSet) – The sequence set of the messages to move.

  • mailbox (Mailbox) – The destination mailbox.

command: ClassVar[bytes] = b'MOVE'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[MoveCommand, memoryview]

class pymap.parsing.command.select.FetchCommand(tag, seq_set, attr_list, options=None)[source]

The FETCH command fetches message data from the selected mailbox. What data is fetched can be controlled in depth by a set of fetch attributes given in the command.

See also

RFC 3501 6.4.5.

Parameters:
command: ClassVar[bytes] = b'FETCH'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[FetchCommand, memoryview]

class pymap.parsing.command.select.StoreCommand(tag, seq_set, flags, mode, silent, options=None)[source]

The STORE command updates the flags of a set of messages in the selected mailbox.

See also

RFC 3501 6.4.6.

Parameters:
  • tag (bytes) – The command tag.

  • seq_set (SequenceSet) – The sequence set of the messages to fetch.

  • flags (Iterable[Flag]) – The flag set operand.

  • mode (FlagOp) – The type of update operation.

  • silent (bool) –

  • options (ExtensionOptions | None) –

command: ClassVar[bytes] = b'STORE'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[StoreCommand, memoryview]

class pymap.parsing.command.select.SearchCommand(tag, keys, charset, options=None)[source]

The SEARCH command searches the messages in the selected mailbox based on a set of search criteria.

See also

RFC 3501 6.4.4.

Parameters:
  • tag (bytes) – The command tag.

  • keys (Iterable[SearchKey]) – The search keys.

  • charset (str | None) – The charset in use by the search keys.

  • options (ExtensionOptions | None) –

command: ClassVar[bytes] = b'SEARCH'

The command key, e.g. b'NOOP'.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[SearchCommand, memoryview]

class pymap.parsing.command.select.UidCommand(tag)[source]

The UID command precedes one of the COPY, EXPUNGE, FETCH, SEARCH, or STORE commands and indicates that the command interacts with message UIDs instead of sequence numbers. Refer to the RFC section for a complete description.

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'UID'

The command key, e.g. b'NOOP'.

compound: ClassVar[bool] = True

True if the command is part of a compound command.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidCommand, memoryview]

class pymap.parsing.command.select.UidCopyCommand(tag, seq_set, mailbox)[source]

The UID COPY variant of the COPY command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID COPY'

The command key, e.g. b'NOOP'.

delegate

alias of CopyCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidCopyCommand, memoryview]

class pymap.parsing.command.select.UidMoveCommand(tag, seq_set, mailbox)[source]

The UID MOVE variant of the MOVE command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID MOVE'

The command key, e.g. b'NOOP'.

delegate

alias of MoveCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidMoveCommand, memoryview]

class pymap.parsing.command.select.UidExpungeCommand(tag, uid_set=None)[source]

The UID EXPUNGE variant of the EXPUNGE command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID EXPUNGE'

The command key, e.g. b'NOOP'.

delegate

alias of ExpungeCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidExpungeCommand, memoryview]

class pymap.parsing.command.select.UidFetchCommand(tag, seq_set, attr_list, options=None)[source]

The UID FETCH variant of the FETCH command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID FETCH'

The command key, e.g. b'NOOP'.

delegate

alias of FetchCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidFetchCommand, memoryview]

class pymap.parsing.command.select.UidSearchCommand(tag, keys, charset, options=None)[source]

The UID SEARCH variant of the SEARCH command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID SEARCH'

The command key, e.g. b'NOOP'.

delegate

alias of SearchCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidSearchCommand, memoryview]

class pymap.parsing.command.select.UidStoreCommand(tag, seq_set, flags, mode, silent, options=None)[source]

The UID STORE variant of the STORE command, which uses message UIDs instead of sequence numbers.

Parameters:
command: ClassVar[bytes] = b'UID STORE'

The command key, e.g. b'NOOP'.

delegate

alias of StoreCommand

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[UidStoreCommand, memoryview]

class pymap.parsing.command.select.IdleCommand(tag)[source]

The IDLE command waits for the continuation string DONE from the client. During this wait, the server may be sending untagged responses indicating concurrent updates to the mailbox.

Parsing this command is a special case. The continuation string DONE is actually parsed by the parse_done() method. The parse() only parses the IDLE <CRLF> portion, and does not raise a RequiresContinuation exception.

See also

RFC 2177

Parameters:

tag (bytes) –

command: ClassVar[bytes] = b'IDLE'

The command key, e.g. b'NOOP'.

continuation = b'DONE'

The string used to end the command.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[IdleCommand, memoryview]

parse_done(buf)[source]

Parse the continuation line sent by the client to end the IDLE command.

Parameters:

buf (memoryview) – The continuation line to parse.

Return type:

tuple[bool, memoryview]

pymap.parsing.primitives

Primitive parseable objects in the IMAP protocol.

class pymap.parsing.primitives.Nil[source]

Represents a NIL object from an IMAP stream.

property value: None

Always returns None.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Nil, memoryview]

class pymap.parsing.primitives.Number(num)[source]

Represents a number object from an IMAP stream.

Parameters:

num (int) – The integer value.

property value: int

The integer value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Number, memoryview]

class pymap.parsing.primitives.Atom(value)[source]

Represents an atom object from an IMAP stream.

Parameters:

value (bytes) – The atom bytestring.

property value: bytes

The atom bytestring.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Atom, memoryview]

class pymap.parsing.primitives.List(items, sort=False)[source]

Represents a list of Parseable objects from an IMAP stream.

Parameters:
  • items (Iterable[MaybeBytes]) – The list of parsed objects.

  • sort (bool) – If True, the list of items is sorted.

property value: FrozenList[bytes | SupportsBytes]

The list of parsed objects.

get_as(cls: ParseableType[ParseableT]) Sequence[ParseableT][source]
get_as(cls: type[MaybeBytesT]) Sequence[MaybeBytesT]

Return the list of parsed objects.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[List, memoryview]

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.primitives.String[source]

Represents a string object from an IMAP string. This object may not be instantiated directly, use one of its derivatives instead.

abstract property binary: bool

True if the string should be transmitted as binary.

abstract property length: int

The length of the string value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[String, memoryview]

classmethod build(value, binary=False, fallback=None)[source]

Produce either a QuotedString or LiteralString based on the contents of data. This is useful to improve readability of response data.

Parameters:
  • value (object) – The string to serialize.

  • binary (bool) – True if the string should be transmitted as binary.

  • fallback (object) – The default value to use if value is None.

Return type:

Nil | String

class pymap.parsing.primitives.QuotedString(string, raw=None)[source]

Represents a string object from an IMAP stream that was encased in double-quotes.

Parameters:
  • string (bytes) – The string value.

  • raw (bytes | None) –

property value: bytes

The string value.

property binary: bool

True if the string should be transmitted as binary.

property length: int

The length of the string value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[QuotedString, memoryview]

class pymap.parsing.primitives.LiteralString(string, binary=False)[source]

Represents a string object from an IMAP stream that used the literal syntax.

Parameters:
  • string (bytes | Writeable) – The literal string value.

  • binary (bool) – True if the string is considered binary data.

property value: bytes

The primary value associated with the parsed data.

property binary: bool

True if the string should be transmitted as binary.

property length: int

The length of the string value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[LiteralString, memoryview]

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

pymap.parsing.specials

class pymap.parsing.specials.astring.AString(string, raw=None)[source]

Represents a string that may have quotes (like a quoted-string) or may not (like an atom). Additionally allows the closing square bracket (]) character in the unquoted form.

Parameters:
  • string (bytes) – The string value.

  • raw (bytes | None) – The raw bytestring from IMAP parsing.

string

The string value.

property value: bytes

The string value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[AString, memoryview]

class pymap.parsing.specials.datetime_.DateTime(when, raw=None)[source]

Represents a date-time quoted string from an IMAP stream.

Parameters:
  • when (datetime) – The date-time value.

  • raw (bytes | None) – The raw bytestring from IMAP parsing.

property value: datetime

The date-time value.

classmethod get_local_tzinfo()[source]

The system timezone, used when no timezone is specified.

Return type:

tzinfo | None

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[DateTime, memoryview]

class pymap.parsing.specials.fetchattr.FetchPartial(start, length=None)[source]

Used to indicate that only a substring of the desired fetch is being requested.

Parameters:
  • start (int) – The first octet of the requested substring.

  • length (int | None) – The maximum length of the requested substring, or None.

class pymap.parsing.specials.fetchattr.FetchRequirement(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Indicates the data required to fulfill a message fetch.

NONE

No data is required.

METADATA

The IMAP metadata is required.

HEADER

The message header is required.

BODY

The parsed MIME message body is required.

has_all(expected)[source]

Returns true if all of the expected fetch requirements are met by this fetch requirement.

Parameters:

expected (FetchRequirement) – The expected fetch requirements.

Return type:

bool

has_none(expected)[source]

Returns true if none of the expected fetch requirements are met by this fetch requirement.

Parameters:

expected (FetchRequirement) – The expected fetch requirements.

Return type:

bool

classmethod get_all()[source]

Return all possible fetch requirements reduced into a single requirement.

Return type:

FetchRequirement

classmethod reduce(requirements)[source]

Reduce a set of fetch requirements into a single requirement.

Parameters:

requirements (Iterable[FetchRequirement]) – The set of fetch requirements.

Return type:

FetchRequirement

class pymap.parsing.specials.fetchattr.FetchAttribute(attribute, section=None, partial=None)[source]

Represents an attribute that should be fetched for each message in the sequence set of a FETCH command on an IMAP stream.

Parameters:
section

The attribute section.

partial

The attribute partial range.

class Section(parts, specifier=None, headers=None)[source]

Represents a fetch attribute section, which typically comes after the attribute name within square brackets, e.g. BODY[1.TEXT].

Parameters:
  • parts (Sequence[int]) – The nested MIME part identifiers.

  • specifier (bytes | None) – The MIME part specifier.

  • headers (frozenset[bytes] | None) – The MIME part specifier headers.

property value: bytes

The attribute name.

property requirement: FetchRequirement

Indicates the data required to fulfill this fetch attribute.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[FetchAttribute, memoryview]

class pymap.parsing.specials.fetchattr.FetchValue(attribute)[source]

A value fetched from a message for a single fetch attribute.

Parameters:

attribute (FetchAttribute) – The fetch attribute.

class pymap.parsing.specials.flag.Flag(value)[source]

Represents a message flag from an IMAP stream.

Parameters:

value (str | bytes) – The flag or keyword value.

property value: bytes

The flag or keyword value.

property is_system: bool

True if the flag is an RFC-defined IMAP system flag.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Flag, memoryview]

pymap.parsing.specials.flag.get_system_flags()[source]

Return the set of implemented system flags.

Return type:

frozenset[Flag]

pymap.parsing.specials.flag.Seen = <Flag value=b'\\Seen'>

The \\Seen system flag.

pymap.parsing.specials.flag.Recent = <Flag value=b'\\Recent'>

The \\Recent system flag.

pymap.parsing.specials.flag.Deleted = <Flag value=b'\\Deleted'>

The \\Deleted system flag.

pymap.parsing.specials.flag.Flagged = <Flag value=b'\\Flagged'>

The \\Flagged system flag.

pymap.parsing.specials.flag.Answered = <Flag value=b'\\Answered'>

The \\Answered system flag.

pymap.parsing.specials.flag.Draft = <Flag value=b'\\Draft'>

The \\Draft system flag.

pymap.parsing.specials.flag.Wildcard = <Flag value=b'\\*'>

The \\* special wildcard flag.

class pymap.parsing.specials.mailbox.Mailbox(mailbox)[source]

Represents a mailbox data object from an IMAP stream.

Parameters:

mailbox (str) – The mailbox name.

property value: str

The mailbox name.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Mailbox, memoryview]

class pymap.parsing.specials.objectid.ObjectId(object_id=None)[source]

Represents an object ID, used to identify a mailbox, message, or thread.

An object_id value of None is a special case indicating that this object ID is not defined.

Parameters:

object_id (bytes | None) – The object ID bytestring, or None.

See also

RFC 8474

property value: bytes

The object ID value.

property parens: bytes

The object ID value surrounded by parentheses.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[ObjectId, memoryview]

classmethod new(prefix, digest)[source]

Return a new object ID from a hash digest.

Parameters:
  • prefix (bytes) – The prefix for the object ID.

  • digest (bytes) – The hash digest.

Return type:

ObjectId

classmethod new_mailbox_id(digest)[source]

Return a new mailbox ID from a hash digest.

Parameters:

digest (bytes) – The hash digest.

Return type:

ObjectId

classmethod new_email_id(digest)[source]

Return a new email ID from a hash digest.

Parameters:

digest (bytes) – The hash digest.

Return type:

ObjectId

classmethod new_thread_id(digest)[source]

Return a new thread ID from a hash digest.

Parameters:

digest (bytes) – The hash digest.

Return type:

ObjectId

classmethod random(prefix)[source]

Return a new randomized object ID.

Parameters:

prefix (bytes) – The prefix for the object ID.

Return type:

ObjectId

classmethod random_mailbox_id()[source]

Return a new randomized mailbox ID.

Return type:

ObjectId

classmethod random_email_id()[source]

Return a new randomized email ID.

Return type:

ObjectId

classmethod random_thread_id()[source]

Return a new randomized thread ID.

Return type:

ObjectId

classmethod maybe(value)[source]

Return an object ID representing the string or bytestring value. If the input is empty or None, the object ID returned will have not_defined be true.

Parameters:

value (AnyStr | None) – The object ID string or bytestring.

Return type:

ObjectId

class pymap.parsing.specials.options.ExtensionOption(option, arg)[source]

Represents a single command option, which may or may not have an associated value.

See also

RFC 4466 2.1.

Parameters:
  • option (bytes) – The name of the option.

  • arg (List) – The option argument, if any.

property value: bytes

The primary value associated with the parsed data.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[ExtensionOption, memoryview]

class pymap.parsing.specials.options.ExtensionOptions(options)[source]

Represents a set of command options, which may or may not have an associated argument. Command options are always optional, so the parsing will not fail, it will just return an empty object.

See also

RFC 4466 2.1.

Parameters:

options (Iterable[ExtensionOption]) – The mapping of options to argument.

classmethod empty()[source]

Return an empty set of command options.

Return type:

ExtensionOptions

property value: Mapping[bytes, List]

The primary value associated with the parsed data.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[ExtensionOptions, memoryview]

class pymap.parsing.specials.searchkey.SearchKey(key, filter_=None, inverse=False)[source]

Represents a search key given to the SEARCH command on an IMAP stream.

Parameters:
  • key (bytes) – The search key.

  • filter – The filter object, used by most search keys.

  • inverse (bool) – If the search key was inverted with NOT.

  • filter – The filter object, used by most search keys.

  • inverse – If the search key was inverted with NOT.

  • filter_ (_FilterType | None) –

property value: bytes

The search key.

property value_str: str

The search key, as a string.

property requirement: FetchRequirement

Indicates the data required to fulfill this search key.

property not_inverse: SearchKey

Return a copy of the search key with inverse flipped.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[SearchKey, memoryview]

class pymap.parsing.specials.sequenceset.MaxValue[source]

The type used as a placeholder for the maximum value.

class pymap.parsing.specials.sequenceset.SequenceSet(sequences, uid=False)[source]

Represents a sequence set from an IMAP stream.

Parameters:
  • sequences (Sequence[_SeqElem]) – The sequence set data.

  • uid (bool) – True if the sequences refer to message UIDs.

uid

True if the sequences refer to message UIDs.

classmethod all(uid=False)[source]

A sequence set intended to contain all values.

Parameters:

uid (bool) –

Return type:

SequenceSet

property value: Sequence[MaxValue | int | tuple[MaxValue | int, MaxValue | int]]

The sequence set data.

property is_all: bool

True if the sequence set starts at 1 and ends at the maximum value.

This may be used to optimize cases of checking for a value in the set, avoiding the need to provide max_value in flatten() or iter().

flatten(max_value)[source]

Return a set of all values contained in the sequence set.

Parameters:

max_value (int) – The maximum value, in place of any *.

Return type:

frozenset[int]

iter(max_value)[source]

Iterates through the sequence numbers contained in the set, bounded by the given maximum value (in place of any *).

Parameters:

max_value (int) – The maximum value of the set.

Return type:

Iterator[int]

classmethod build(seqs, uid=False)[source]

Build a new sequence set that contains the given values using as few groups as possible.

Parameters:
  • seqs (Iterable[int]) – The sequence values to build.

  • uid (bool) – True if the sequences refer to message UIDs.

Return type:

SequenceSet

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[SequenceSet, memoryview]

class pymap.parsing.specials.statusattr.StatusAttribute(status)[source]

Represents a status attribute from an IMAP stream.

Parameters:

status (bytes) – The status attribute string.

valid_statuses = {b'MAILBOXID', b'MESSAGES', b'RECENT', b'UIDNEXT', b'UIDVALIDITY', b'UNSEEN'}

The set of valid status attributes.

property value: bytes

The status attribute string.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[StatusAttribute, memoryview]

class pymap.parsing.specials.tag.Tag(tag)[source]

Represents the tag prefixed to every client command in an IMAP stream.

Parameters:

tag (bytes) – The tag value.

property value: bytes

The tag value.

classmethod parse(buf, params)[source]

Implemented by sub-classes to define how to parse the given buffer.

Parameters:
  • buf (memoryview) – The bytes containing the data to be parsed.

  • params (Params) – The parameters used by some parseable types.

Return type:

tuple[Tag, memoryview]

pymap.parsing.response

class pymap.parsing.response.ResponseCode[source]

Base class for response codes that may be returned along with IMAP server responses.

classmethod of(code: None) None[source]
classmethod of(code: bytes | SupportsBytes) ResponseCode

Build and return an anonymous response code object.

Parameters:

code – The code string, without square brackets.

class pymap.parsing.response.Response(tag, text=None, code=None)[source]

Base class for all responses sent from the server to the client. These responses may be sent unsolicited (e.g. idle timeouts) or in response to a tagged command from the client.

Parameters:
  • tag (MaybeBytes) – The tag bytestring of the associated command, a plus (+) to indicate a continuation requirement, or an asterisk (*) to indicate an untagged response.

  • text (MaybeBytes | None) – The response text.

  • code (ResponseCode | None) – Optional response code.

tag

The tag bytestring.

condition: bytes | None = None

The condition bytestring, e.g. OK.

property text: bytes

The response text.

property code: ResponseCode | None

Optional response code.

property is_terminal: bool

True if the response contained an untagged BYE response indicating that the session should be terminated.

property is_bad: bool

True if the response indicates an error in the command received from the client.

async async_write(writer)[source]

Like write(), but allows for asynchronous processing that might be necessary for some responses.

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.response.CommandResponse(tag, text=None, code=None)[source]

A response sent to finish the response to a command. The tag must correspond to the tag given in the command. Untagged responses may precede the command response, according to the rules of the command.

Parameters:
  • tag (MaybeBytes) – The tag bytestring of the associated command.

  • text (MaybeBytes | None) – The response text.

  • code (ResponseCode | None) – Optional response code.

add_untagged(*responses)[source]

Add an untagged response. These responses are shown before the command response.

Parameters:

responses (UntaggedResponse) – The untagged responses to add.

Return type:

None

add_untagged_ok(text, code=None)[source]

Add an untagged OK response.

Parameters:
Return type:

None

property is_terminal: bool

True if the response contained an untagged BYE response indicating that the session should be terminated.

async async_write(writer)[source]

Like write(), but allows for asynchronous processing that might be necessary for some responses.

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.response.UntaggedResponse(text=None, code=None, *, condition=None, writing_hook=None)[source]

A response issued prior to a CommandResponse, which may include details results from the command or updated mailbox state.

Parameters:
  • text (MaybeBytes | None) – The response text.

  • code (ResponseCode | None) – Optional response code.

  • condition (bytes | None) – A condition string, e.g. OK.

  • writing_hook (_WritingHook | None) – An async context manager to enter while the untagged response is being written.

property merge_key: Hashable

Returns a hashable value which can be compared to other merge_key values of the same response type to see if the two responses can be merged.

Raises:

TypeError – This response type may not be merged.

merge(other)[source]

Return a copy of this response with the other response merged in.

Parameters:
Raises:
  • TypeError – This response type may not be merged.

  • ValueError – The two responses are not mergeable.

Return type:

ResponseT

async async_write(writer)[source]

Like write(), but allows for asynchronous processing that might be necessary for some responses.

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.response.ResponseContinuation(text)[source]

Class used for server responses that indicate a continuation requirement. This is when the server needs more data from the client to finish handling the command. The AUTHENTICATE command and any command that uses a literal string argument will send this response as needed.

Parameters:

text (MaybeBytes) – The continuation text.

class pymap.parsing.response.ResponseBad(tag, text, code=None)[source]

BAD response indicating the server encountered a protocol-related error in responding to the command.

Parameters:
  • tag (MaybeBytes) – The tag bytestring to associate the response to a command.

  • text (MaybeBytes) – The response text.

  • code (ResponseCode | None) – Optional response code.

condition: bytes | None = b'BAD'

The condition bytestring, e.g. OK.

property is_bad: bool

True if the response indicates an error in the command received from the client.

class pymap.parsing.response.ResponseNo(tag, text, code=None)[source]

NO response indicating the server successfully parsed the command but failed to execute it successfully.

Parameters:
  • tag (MaybeBytes) – The tag bytestring to associate the response to a command.

  • text (MaybeBytes) – The response text.

  • code (ResponseCode | None) – Optional response code.

condition: bytes | None = b'NO'

The condition bytestring, e.g. OK.

class pymap.parsing.response.ResponseOk(tag, text=None, code=None)[source]

OK response indicating the server successfully parsed and executed the command.

Parameters:
  • tag (MaybeBytes) – The tag bytestring to associate the response to a command.

  • text (MaybeBytes | None) – The response text.

  • code (ResponseCode | None) – Optional response code.

condition: bytes | None = b'OK'

The condition bytestring, e.g. OK.

class pymap.parsing.response.ResponseBye(text=None, code=None, *, condition=None, writing_hook=None)[source]

BYE response indicating that the server will be closing the connection immediately after sending the response is sent. This may be sent in response to a command (e.g. LOGOUT) or unsolicited.

Parameters:
  • text (MaybeBytes | None) – The reason for disconnection.

  • code (ResponseCode | None) – Optional response code.

  • condition (bytes | None) –

  • writing_hook (_WritingHook | None) –

condition: bytes | None = b'BYE'

The condition bytestring, e.g. OK.

property is_terminal: bool

This response is always terminal.

class pymap.parsing.response.ResponsePreAuth(tag, text, code=None)[source]

PREAUTH response during server greeting to indicate the client is already logged in.

Parameters:
  • tag (MaybeBytes) – The tag bytestring to associate the response to a command.

  • text (MaybeBytes) – The response text.

  • code (ResponseCode | None) – Optional response code.

condition: bytes | None = b'PREAUTH'

The condition bytestring, e.g. OK.

class pymap.parsing.response.ResponseT

Type variable with an upper bound of Response.

alias of TypeVar(‘ResponseT’, bound=Response)

class pymap.parsing.response.code.Capability(server_capabilities)[source]

Lists the capabilities the server advertises to the client.

Parameters:

server_capabilities (Iterable[MaybeBytes]) – The list of capabilities to advertise.

property string: bytes

The capabilities string without the enclosing square brackets.

class pymap.parsing.response.code.PermanentFlags(flags)[source]

Indicates the permanent flags available in a mailbox.

Parameters:

flags (Iterable[MaybeBytes]) – The flags to return.

class pymap.parsing.response.code.UidNext(next_)[source]

Indicates the next unique identifier value of the mailbox.

Parameters:
  • next – The next available message UID.

  • next_ (int) –

class pymap.parsing.response.code.UidValidity(validity)[source]

Indicates the mailbox unique identifier validity value.

Parameters:

validity (int) – The UID validity value.

class pymap.parsing.response.code.Unseen(next_)[source]

Indicates the message sequence ID of the first message without the \Seen flag.

Parameters:
  • next – The sequence ID of the message.

  • next_ (int) –

class pymap.parsing.response.code.AppendUid(validity, uids)[source]

Indicates the newly assigned UIDs and UIDVALIDITY of messages appended to a mailbox.

Parameters:
  • validity (int) – The UID validity value.

  • uids (Iterable[int]) – The UIDs of the appended messages.

See also

RFC 4315 3.

class pymap.parsing.response.code.CopyUid(validity, uids)[source]

Indicates the original and newly assigned UIDs and UIDVALIDITY of messages appended to the mailbox.

Parameters:
  • validity (int) – The UID validity value.

  • uids (Iterable[tuple[int, int]]) – The pairs of source UID mapped to destination UID.

See also

RFC 4315 3.

class pymap.parsing.response.code.MailboxId(object_id)[source]

Indicates the mailbox ID, which can be used to correlate mailboxes between renames.

Parameters:

object_id (ObjectId) – The mailbox ID bytestring.

class pymap.parsing.response.fetch.EnvelopeStructure(date, subject, from_, sender, reply_to, to, cc, bcc, in_reply_to, message_id)[source]

Builds the response to an RFC 3501 7.4.2 FETCH ENVELOPE request.

Parameters:
  • date (DateHeader | None) – Original date of the message.

  • subject (UnstructuredHeader | None) – Subject: header.

  • fromFrom: headers.

  • sender (Sequence[SingleAddressHeader] | None) – Sender: headers.

  • reply_to (Sequence[AddressHeader] | None) – Reply-To: headers.

  • to (Sequence[AddressHeader] | None) – To: headers.

  • cc (Sequence[AddressHeader] | None) – Cc: headers.

  • bcc (Sequence[AddressHeader] | None) – Bcc headers.

  • in_reply_to (UnstructuredHeader | None) – In-Reply-To: header.

  • message_id (UnstructuredHeader | None) – Message-Id: header.

  • from_ (Sequence[AddressHeader] | None) –

classmethod empty()[source]

Return an empty envelope structure object.

See also

RFC 2180 4.1.3

Return type:

EnvelopeStructure

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.response.fetch.BodyStructure(maintype, subtype, content_type_params, content_disposition, content_language, content_location)[source]

Parent class for the response to an RFC 3501 7.4.2 FETCH BODYSTRUCTURE request. This class should not be used directly.

Parameters:
  • maintype (str) – Main-type of the Content-Type: header.

  • subtype (str) – Sub-type of the Content-Type: header.

  • content_type_params (Mapping[str, Any] | None) – Parameters from the Content-Type: header.

  • content_disposition (ContentDispositionHeader | None) – Content-Disposition: header.

  • content_language (UnstructuredHeader | None) – Content-Language: header.

  • content_location (UnstructuredHeader | None) – Content-Location: header.

classmethod empty()[source]

Return an empty body structure object.

See also

RFC 2180 4.1.3

Return type:

BodyStructure

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

property extended: List

The body structure attributes with extension data.

class pymap.parsing.response.fetch.MultipartBodyStructure(subtype, content_type_params, content_disposition, content_language, content_location, parts)[source]

BodyStructure sub-class for multipart/* messages. The response is made up of the BODYSTRUCTUREs of all sub-parts.

Parameters:
  • subtype (str) – Sub-type of the Content-Type: header.

  • content_type_params (Mapping[str, Any] | None) – Parameters from the Content-Type: header.

  • content_disposition (ContentDispositionHeader | None) – Content-Disposition: header.

  • content_language (UnstructuredHeader | None) – Content-Language: header.

  • content_location (UnstructuredHeader | None) – Content-Location: header.

  • parts (Sequence[BodyStructure]) – Sub-part body structure objects.

property extended: List

The body structure attributes with extension data.

class pymap.parsing.response.fetch.ContentBodyStructure(maintype, subtype, content_type_params, content_disposition, content_language, content_location, content_id, content_description, content_transfer_encoding, body_md5, size)[source]

BodyStructure sub-class for any content type that does not fit the other sub-classes.

Parameters:
  • maintype (str) – Main-type of the Content-Type: header.

  • subtype (str) – Sub-type of the Content-Type: header.

  • content_type_params (Mapping[str, Any] | None) – Parameters from the Content-Type: header.

  • content_disposition (ContentDispositionHeader | None) – Content-Disposition: header.

  • content_language (UnstructuredHeader | None) – Content-Language: header.

  • content_location (UnstructuredHeader | None) – Content-Location: header.

  • content_id (UnstructuredHeader | None) – Content-Id: header.

  • content_description (UnstructuredHeader | None) – Content-Description: header.

  • content_transfer_encoding (_CTEHeader | None) – Content-Transfer-Encoding: header.

  • body_md5 (str | None) – MD5 hash of the body content.

  • size (int) – Size of the message body, in bytes.

property extended: List

The body structure attributes with extension data.

class pymap.parsing.response.fetch.TextBodyStructure(subtype, content_type_params, content_disposition, content_language, content_location, content_id, content_description, content_transfer_encoding, body_md5, size, lines)[source]

BodyStructure sub-class for text/* messages.

Parameters:
  • subtype (str) – Sub-type of the Content-Type: header.

  • content_type_params (Mapping[str, Any] | None) – Parameters from the Content-Type: header.

  • content_disposition (ContentDispositionHeader | None) – Content-Disposition: header.

  • content_language (UnstructuredHeader | None) – Content-Language: header.

  • content_location (UnstructuredHeader | None) – Content-Location: header.

  • content_id (UnstructuredHeader | None) – Content-Id: header.

  • content_description (UnstructuredHeader | None) – Content-Description: header.

  • content_transfer_encoding (_CTEHeader | None) – Content-Transfer-Encoding: header.

  • body_md5 (str | None) – MD5 hash of the body content.

  • size (int) – Size of the message body, in bytes.

  • lines (int) – Length of the message body, in lines.

property extended: List

The body structure attributes with extension data.

class pymap.parsing.response.fetch.MessageBodyStructure(content_type_params, content_disposition, content_language, content_location, content_id, content_description, content_transfer_encoding, body_md5, size, lines, envelope_structure, body_structure)[source]

BodyStructure sub-class for message/rfc822 messages.

Parameters:
  • content_type_params (Mapping[str, Any] | None) – Parameters from the Content-Type: header.

  • content_disposition (ContentDispositionHeader | None) – Content-Disposition: header.

  • content_language (UnstructuredHeader | None) – Content-Language: header.

  • content_location (UnstructuredHeader | None) – Content-Location: header.

  • content_id (UnstructuredHeader | None) – Content-Id: header.

  • content_description (UnstructuredHeader | None) – Content-Description: header.

  • content_transfer_encoding (_CTEHeader | None) – Content-Transfer-Encoding: header.

  • body_md5 (str | None) – MD5 hash of the body content.

  • size (int) – Size of the message body, in bytes.

  • lines (int) – Length of the message body, in lines.

  • envelope_structure (EnvelopeStructure) – Contained message’s envelope structure.

  • body_structure (BodyStructure) – Contained message’s body structure.

property extended: List

The body structure attributes with extension data.

class pymap.parsing.response.specials.FlagsResponse(flags)[source]

Constructs the special FLAGS response used by the SELECT and EXAMINE commands.

Parameters:

flags (Iterable[MaybeBytes]) – Flags in the response.

property text: bytes

The response text.

class pymap.parsing.response.specials.ExistsResponse(num)[source]

Constructs the special EXISTS response used by the SELECT and EXAMINE commands.

Parameters:

num (int) – The number of messages existing in the mailbox.

property text: bytes

The response text.

class pymap.parsing.response.specials.RecentResponse(num)[source]

Constructs the special RECENT response used by the SELECT and EXAMINE commands.

Parameters:

num (int) – The number of recent messages in the mailbox.

property text: bytes

The response text.

class pymap.parsing.response.specials.ExpungeResponse(seq)[source]

Constructs the special EXPUNGE response used by the EXPUNGE command.

Parameters:

seq (int) – The message sequence number.

property text: bytes

The response text.

class pymap.parsing.response.specials.FetchResponse(seq, data, *, writing_hook=None)[source]

Constructs the special FETCH response used by the STORE and FETCH commands.

Parameters:
  • seq (int) – The message sequence number.

  • data (Iterable[FetchValue]) – Fetch attributes and values for the message.

  • writing_hook (_WritingHook | None) – An async context manager to enter while the untagged response is being written.

property merge_key: int

Returns a hashable value which can be compared to other merge_key values of the same response type to see if the two responses can be merged.

Raises:

TypeError – This response type may not be merged.

merge(other)[source]

Merge the other FETCH response, adding any fetch attributes that do not already exist in this FETCH response. For example:

* 3 FETCH (UID 119)
* 3 FETCH (FLAGS (\Seen))

Would merge into:

* 3 FETCH (UID 119 FLAGS (\Seen))
Parameters:

other (FetchResponse) – The other response to merge.

Return type:

FetchResponse

property text: bytes

The response text.

write(writer)[source]

Write the object to the stream, with one or more calls to write().

Parameters:

writer (WriteStream) – The output stream.

Return type:

None

class pymap.parsing.response.specials.SearchResponse(seqs)[source]

Constructs the special SEARCH response used by the SEARCH command.

Parameters:

seqs (Iterable[int]) – List of message sequence integers.

property text: bytes

The response text.

class pymap.parsing.response.specials.ESearchResponse(issuer_tag, uid, data)[source]

Constructs the special ESEARCH response used by extended SEARCH commands. This response should be mutually exclusive with SEARCH responses.

See also

RFC 4466 2.6.2.

Parameters:
  • issuer_tag (bytes | None) – The command tag, if issued in response to a command.

  • uid (bool) – True if the response refers to message UIDs.

  • data (Mapping[bytes, MaybeBytes]) – The returned search data pairs.

property text: bytes

The response text.

class pymap.parsing.response.specials.StatusResponse(name, data)[source]

Constructs the special STATUS response used by the STATUS command.

Parameters:
  • name (str) – The name of the mailbox.

  • data (Mapping[StatusAttribute, MaybeBytes]) – Dictionary mapping status attributes to their values.

property text: bytes

The response text.

class pymap.parsing.response.specials.ListResponse(mailbox, sep, attrs)[source]

Constructs the special LIST response used by the LIST command.

Parameters:
  • mailbox (str) – The mailbox name.

  • sep (str | None) – The heirarchy separation character.

  • attrs (Iterable[bytes]) – The attribute flags associated with the mailbox.

property text: bytes

The response text.

class pymap.parsing.response.specials.LSubResponse(mailbox, sep, attrs)[source]

Constructs the special LSUB response used by the LSUB command.

Parameters:
  • mailbox (str) –

  • sep (str | None) –

  • attrs (Iterable[bytes]) –

class pymap.parsing.response.specials.IdResponse(parameters)[source]

Constructs the untagged ID response used by the ID command.

Parameters:

parameters (Parameters | None) – Optional mapping of key/value parameters sent back to the client.

Parameters

Type alias for the response parameter key/value mapping.

alias of Mapping[bytes, bytes]

property text: bytes

The response text.

pymap.parsing.modutf7

Implements the modified UTF-7 specification used for encoding and decoding mailbox names in IMAP.

See also

RFC 3501 5.1.3

pymap.parsing.modutf7.modutf7_encode(data)[source]

Encode the string using modified UTF-7.

Parameters:

data (str) – The input string to encode.

Return type:

bytes

pymap.parsing.modutf7.modutf7_decode(data)[source]

Decode the bytestring using modified UTF-7.

Parameters:

data (bytes) – The encoded bytestring to decode.

Return type:

str

pymap.parsing.message

class pymap.parsing.message.AppendMessage(literal, when=None, flag_set=<factory>, options=<factory>)[source]

A single message from the APPEND command.

Parameters:
  • literal (bytes) – The message literal.

  • when (datetime | None) – The internal timestamp to assign to the message.

  • flag_set (frozenset[Flag]) – The flags to assign to the message.

  • options (ExtensionOptions) – The extension options in use for the message.