Returns the given message encoded in ascii with a format suitable for
        SMTP transmission:

        - Makes sure the message is ASCII encoded ;
        - Normalizes line endings to '\r\n' ;
        - Adds a (second) period at the beginning of lines that start
          with a period ;
        - Makes sure the message ends with '\r\n.\r\n'.

        For further details, please check out RFC 5321 `§ 4.1.1.4`_
        and `§ 4.5.2`_.

        .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4
        .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2

def prepare_message(message):
        """
        Returns the given message encoded in ascii with a format suitable for
        SMTP transmission:

        - Makes sure the message is ASCII encoded ;
        - Normalizes line endings to '\r\n' ;
        - Adds a (second) period at the beginning of lines that start
          with a period ;
        - Makes sure the message ends with '\r\n.\r\n'.

        For further details, please check out RFC 5321 `§ 4.1.1.4`_
        and `§ 4.5.2`_.

        .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4
        .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2
        """
        if isinstance(message, bytes):
            bytes_message = message
        else:
            bytes_message = message.encode("ascii")

        # The original algorithm uses regexes to do this stuff.
        # This one is -IMHO- more pythonic and it is slightly faster.
        #
        # Another version is even faster, but I chose to keep something
        # more pythonic and readable.
        # FYI, the fastest way to do all this stuff seems to be
        # (according to my benchmarks):
        #
        # bytes_message.replace(b"\r\n", b"\n") \
        #              .replace(b"\r", b"\n") \
        #              .replace(b"\n", b"\r\n")
        #
        # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE)
        # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message)
        #
        # if not bytes_message.endswith(b"\r\n"):
        #     bytes_message += b"\r\n"
        #
        # bytes_message += b"\r\n.\r\n"

        lines = []

        for line in bytes_message.splitlines():
            if line.startswith(b"."):
                line = line.replace(b".", b"..", 1)

            lines.append(line)

        # Recompose the message with <CRLF> only:
        bytes_message = b"\r\n".join(lines)

        # Make sure message ends with <CRLF>.<CRLF>:
        bytes_message += b"\r\n.\r\n"

        return bytes_message