Skip to content

Email API Reference

Email(*, mail_from=None, rcpt_to=None, policy=SMTP_DEFAULT_POLICY, cc=None, bcc=None, subject=None, text=None, html=None, charset=UTF_8, headers=None, attachments=None, attachment_strategy=AllFilesStrategy(), preamble=NON_MIME_AWARE_CLIENT_MESSAGE, epilogue=NON_MIME_AWARE_CLIENT_MESSAGE, boundary=None)

An encapsulation of an email message. In cases of multipart email messages this is a tree of Emails. Mailies Email object is treated as a partial mapping, where indexes are based on headers, various utility methods are available for managing message bodies.

An email message is a combination of RFC-2822 headers and a payload. If the message is a container (e.g a multipart message) then the payload is a list of EmailMessage objects, otherwise it is just a string.

Parameters:

Name Type Description Default
mail_from typing.Optional[str]

(Optional) The envelope sender of the email, a compliant email address. If provided this can be automatically deferred when sending the email through the mail SMTPClient. Client send(...) allows overriding this value at runtime. When specified mailie will NOT include this in the email headers as a From header. smtplib cares not about email headers. In order to add a From header to the email pass it explicitly into headers=. When calling send() on the client without specifying the optional mail_from argument, mailie will attempt to fetch the value from the Email instance.

None
rcpt_to typing.Optional[typing.Union[typing.Sequence[str], str]]

(Optional) The envelope recipient(s) of the email, a compliant email address or a Sequence of compliant email addresses. If provided this can be automatically defrred when sending the email through the mailie SMTPClient. Client send(...) allows overriding this value at runtime. When specified mailie will NOT include this in the email headers as a To header. smtplib cares not about email headers. In order to add a To header to the email, pass it explicitly into headers=. When calling send() on the client without specifying the optional mail_to argument, mailie will attempt to fetch the value from the Email instance.

None
policy typing.Union[str, Policy]

(Optional) An instance of email.policy.Policy used for governing disparate use cases. By default mailie will assume a SMTP policy that automatically handles /r/n. In a nutshell; policies are used to customise the behaviour of various classes in pythons inbuilt email package. For more information see: https://docs.python.org/3/library/email.policy.html. Below outlines some of the inbuilt policies available via python email: :: default (uses python line endings via /n - sometimes undesirable) :: SMTP (clone of default, with /r/n line endings for RFC compliance) :: SMTPUTF8 (a UTF-8 equivalent of smtp, useful for non-ASCII in sender/recipient data) :: HTTP (useful if serialising headers for HTTP traffic) :: strict (clone of default, except raise_on_defect is assigned True to prevent silent failures) If omitted by client code, mailie will assume a SMTP strict equivalent by default. If this is undesirable pass your own policy, e.g email.policy.SMTP. For core policies; mailie supports passing a string to resolve the policy e.g policy='SMTPUTF8'.

SMTP_DEFAULT_POLICY
cc typing.Optional[typing.Iterable[str]]

(Optional) A single email address (string) or an iterable of email addresses. In both cases the emails are converted to a list of distinct addresses. Recipients set for cc (carbon copy) are all visible to each other; in order to include a hidden recipient, opt for bcc=... instead. CC recipients are handled via a CC header and are also added to to_addrs and bcc during the SMTP conversation. Including arbitrary headers for CC is not advised as this is handled internally by the Email instance.

None
bcc typing.Optional[typing.Iterable[str]]

(Optional) A single email address (string) or an iterable of email addresses. In both cases the emails are converted to a list of distinct addresses. In older versions of python email handling via a BCC header revealed recipients, but is however fixed using send_message(...). However mailie will not include a BCC header in the email regardless and all to_addrs; cc + bcc addresses will be compressed into a single iterable when having the SMTP conversation. Including arbitrary headers for BCC is not advised as this is handled internally by the Email instance.

None
subject typing.Optional[str]

(Optional) A string to include in the message as part of the subject header. By design emails do not REQUIRE a subject however it is good practice to include one. If omitted the subject of the email will be empty ''. If subject= is provided it will automatically appended into the headers, it is also possible to ignore subject and pass a 'Subject' header directly for the same affect.

None
text typing.Optional[str]

(Optional) A string of text to include as the text/plain payload (body) of the email. By default, an empty body will be created. For simple plaintext mails, text= is the only data necessary, however for more multipart variants html & attachments can be provided.

None
html typing.Optional[str]

(Optional) A tuple of either length 1 or 2. If the tuple is a single element then the value is considered the HTML content in it's unformatted, raw form. An optional iterable of attachment paths can be provided; these will be have CID's generated implicitly and be formatted into the html content provided in the order in which they are provided. For that reason, a tuple is preferred; using a set cannot guarantee the CID for img src tags in the html template post-format processing. A string of html content to include in the payload (body) of the email. By default, html is omitted and a simple plain text mail is built, if provided the mail is converted to a multipart/alternative where the payload includes both plain text and HTML content. Depending on the recipient(s) client, displaying of this will vary however mailie will signal that the HTML is priority (by the order in which the data is transmitted).

None
charset EMAIL_CHARSET_ALIAS

(Optional) ...

UTF_8
headers typing.Optional[typing.Union[typing.List[str], typing.MutableMapping[str, str]]]

(Optional) A list of strings which are RFC-5322 or RFC-6532 compliant, where the header field and the header value are separated by colon. A mapping is also permitted where the colons are omitted such as {"header_field_name": "header_field_value"}

None
attachments typing.Optional[EMAIL_ATTACHMENT_PATH_ALIAS]

(Optional) attachments path can support attaching files from the local file system to the email. It can accept a single path (string or PathLike) or an iterable of paths (string or PathLike). Additionally it can accept the path to a directory in which case all files located in that directory will be considered for attachments. These attachments are NOT inline attachments; to provide inline attachments for the alternative body; pass a 2 length tuple to html=(..., ...).

None
attachment_strategy Attachable

A class which implements the mailie.Attachable interface. This class can be provided by the user at runtime in order implement a customised attachment lookup and attachment process. If omitted mailie will use a basic file strategy that takes paths literally and creates FileAttachment objects out of them, if a directory is provided all files in that directory will be turned into FileAttachments and added to the email (NOT inline). The default strategy does not recursive into sub directories to hunt for more files; implement your own strategy if that is what you desire. What kind of emails are typically sent and currently supported? :: Simple plaintext emails :: Simple alternative plaintext/html emails :: Html emails embedded/inline attachments :: Emails with normal attachments

AllFilesStrategy()

__bool__()

If the Email has any defects returns False.

__contains__(name)

Check if a particular header is present in the email headers. This check is case insensitive and name should omit the trailing colon :.

__delitem__(name)

Deletes all headers of name. If no headers are present this implicitly does nothing.

__getitem__(name)

Ignoring case, retrieve the header with a field value of name. If no header is found no KeyError is raised, but instead None is returned. name does not include the trailing colon :.

__len__()

Return the total number of headers in the message, this tally includes duplicate headers.

__setitem__(name, value)

Adds a new header to the Email where name is the header field_name and value is the field_value respectively. The header is appended to the messages existing headers. This does not overwrite existing headers with the same name, but instead appends possible duplicates. In order to perform an overwrite, consider calling del on the Email instance with the header field name, then appending this header. Email.replace_header(name, value) can be used as a convenience method for replacing a single headers value.

__str__()

Returns the entire email message flattened as a string.

as_bytes(unixfrom=False, policy=None)

Returns the entire email message flattened as a bytes object. If unixfrom is True, the envelope sender is included in the bytes object. policy= can be provided to override the default policy for various aspects of formatting. Flattening the message may trigger changes to the underlying EmailMessage and this method may not be the best way to serialize the message.

as_string(unixfrom=False, maxheaderlen=0, policy=None)

Return the entire email message flattened as a string. If unixfrom is True, the envelope sender is included the string. If maxheaderlen is 0, the underlying policy is used for determining the max_line_length, an additional policy= can be passed to defer to that policy instead.

attach(payload)

Add the given payload to the current payload.

The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead.

clear()

Clears the headers and payload from the delegated EmailMessage messaged. If you want to retain non Content- headers, use clear_content() instead.

clear_content()

Clears the payload and all non Content- headers.

get(name, failobj=None)

Return the value of the header named name. If the header is not present in the message then failobj is returned. Invoked by __getitem__

get_all(name, failobj=None)

Return a list of the header values where name is the header name. If there is no header with that name in the message, then failobj is returned. If the header exists multiple times all of it's values are retruend.

get_content_maintype()

Return the maintype resolved via get_content_type() e.g plain

get_content_subtype()

Return the subtype resolved via get_content_type() e.g text

get_content_type()

Return the emails maintype/subtype. If no Content-Type header exists in the email then get_content_type() is used to determine it. If the Content-Type header is invalid, plain/text is returned.

get_default_type()

Return the default content type.

get_params(failobj=None, header=CONTENT_TYPE_HEADER, unquote=True)

Returns the messages content headers as a list of tuples split on the =. In the cases where no = exists; an empty string is set. Optional failobj is returned in the instance where there is no Content-Type header, header can be provided to change the search context from Content-Type to that particular header.

get_unixfrom()

Retrieve the envelope sender header.

is_multipart()

Return True if the message payload is a list of sub email messages. If is_multipart() returns False the message Email payload should be a string which might be a Content Transfer Encoding binary object.

items()

Return a list of 2-tuples containing all the messages header field and head values respectively.

keys()

Return a list of all the messages header field names.

replace_header(_name, _value)

Convenience method for overwriting an existing header with a new value. This method will replace the first instance of the header with _name. This method returns the Email instance for fluency.

set_default_type(ctype)

Sets the default content type. Returns the Email instance for fluency

set_unixfrom(unixfrom)

Set the messages envelope sender header to unixfrom. This is not a property just to keep API delegation with the underlying EmailMessage.

smtp_arguments() property

Useful attributes for engaging in SMTP communication with this email object. Email from and to headers are used as a fallback if no explicit ones are passed to the mailie clients when sending an email.

tree_view(*, message=None, file=None, level=0)

Write the structure of this message to stdout. This is handled recursively.

values()

Return a list of all the messages header values.