Beispiel #1
0
def get_message(sender, recipient, subject, body, content_type="plain",
                extra_headers=None):
    """Generate a `Message` instance.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may
    contain non-ASCII characters.

    The email will be properly MIME encoded.

    The charset of the email will be the first one out of the list
    that can represent all the characters occurring in the email.
    """

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = _parseaddr(sender)
    recipient_name, recipient_addr = _parseaddr(recipient)

    sender_encoding = guess_encoding(sender_name)
    recipient_encoding = guess_encoding(recipient_name)
    subject_encoding = guess_encoding(subject)
    body_encoding = guess_encoding(body)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(_Header(sender_name, sender_encoding).encode())
    recipient_name = str(_Header(recipient_name, recipient_encoding).encode())

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr.encode('ascii')
    recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    message = _MIMEText(body, content_type, body_encoding)
    message['From'] = _formataddr((sender_name, sender_addr))
    message['To'] = _formataddr((recipient_name, recipient_addr))
    message['Subject'] = _Header(subject, subject_encoding)

    if extra_headers:
        for key, value in extra_headers.items():
            encoding = guess_encoding(value)
            message[key] = _Header(value, encoding)
    return message
Beispiel #2
0
def construct_email(author, targets, subject, message, cc=None):
    if author.pgp_key:
        signers = [author.pgp_key]
    else:
        signers = []
    recipients = [p.pgp_key for p in targets if p.pgp_key]
    encrypt = True
    for person in targets:
        if not person.pgp_key:
            encrypt = False  # cannot encrypt to every recipient
            break
    if cc:
        recipients.extend([p.pgp_key for p in cc if p.pgp_key])
        for person in cc:
            if not person.pgp_key:
                encrypt = False
                break
    if not recipients:
        encrypt = False  # noone to encrypt to
    if signers and encrypt:
        if author.pgp_key not in recipients:
            recipients.append(author.pgp_key)
        message = _pgp_mime.sign_and_encrypt(
            message=message, signers=signers, recipients=recipients,
            always_trust=True)
    elif signers:
        message = _pgp_mime.sign(message=message, signers=signers)
    elif encrypt:
        message = _pgp_mime.encrypt(message=message, recipients=recipients)

    message['Date'] = _email_utils.formatdate()
    message['From'] = get_address(author)
    message['Reply-to'] = message['From']
    message['To'] = ', '.join(
        get_address(target) for target in targets)
    if cc:
        message['Cc'] = ', '.join(
            get_address(target) for target in cc)
    subject_encoding = _pgp_mime.guess_encoding(subject)
    if subject_encoding == 'us-ascii':
        message['Subject'] = subject
    else:
        message['Subject'] = _Header(subject, subject_encoding)

    return message
Beispiel #3
0
def get_message(sender, recipient, subject, body, content_type,
                extra_headers=None, config=None, section='DEFAULT'):
    """Generate a `Message` instance.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded.

    The charset of the email will be the first one out of the list
    that can represent all the characters occurring in the email.

    >>> message = get_message(
    ...     sender='John <*****@*****.**>', recipient='Ζεύς <*****@*****.**>',
    ...     subject='Testing',
    ...     body='Hello, world!\\n',
    ...     content_type='plain',
    ...     extra_headers={'Approved': '*****@*****.**'})
    >>> print(message.as_string())  # doctest: +REPORT_UDIFF
    MIME-Version: 1.0
    Content-Type: text/plain; charset="us-ascii"
    Content-Transfer-Encoding: 7bit
    From: John <*****@*****.**>
    To: =?utf-8?b?zpbOtc+Nz4I=?= <*****@*****.**>
    Subject: Testing
    Approved: [email protected]
    <BLANKLINE>
    Hello, world!
    <BLANKLINE>
    """
    if config is None:
        config = _config.CONFIG
    if section not in config.sections():
        section = 'DEFAULT'
    encodings = [
        x.strip() for x in config.get(section, 'encodings').split(',')]

    # Split real name (which is optional) and email address parts
    sender_name,sender_addr = _parseaddr(sender)
    recipient_name,recipient_addr = _parseaddr(recipient)

    sender_encoding = guess_encoding(sender_name, encodings)
    recipient_encoding = guess_encoding(recipient_name, encodings)
    subject_encoding = guess_encoding(subject, encodings)
    body_encoding = guess_encoding(body, encodings)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(_Header(sender_name, sender_encoding).encode())
    recipient_name = str(_Header(recipient_name, recipient_encoding).encode())

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr.encode('ascii')
    recipient_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    message = _MIMEText(body, content_type, body_encoding)
    message['From'] = _formataddr((sender_name, sender_addr))
    message['To'] = _formataddr((recipient_name, recipient_addr))
    message['Subject'] = _Header(subject, subject_encoding)
    if config.getboolean(section, 'use-8bit'):
        del message['Content-Transfer-Encoding']
        charset = _Charset(body_encoding)
        charset.body_encoding = _email_encoders.encode_7or8bit
        message.set_payload(body, charset=charset)
    if extra_headers:
        for key,value in extra_headers.items():
            encoding = guess_encoding(value, encodings)
            message[key] = _Header(value, encoding)
    return message
def Header(name):  # noqa
    return _Header(name, 'utf-8').encode()
Beispiel #5
0
def get_message(sender,
                recipient,
                subject,
                body,
                content_type,
                extra_headers=None,
                config=None,
                section='DEFAULT'):
    """Generate a `Message` instance.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded.

    The charset of the email will be the first one out of the list
    that can represent all the characters occurring in the email.

    >>> message = get_message(
    ...     sender='John <*****@*****.**>', recipient='Ζεύς <*****@*****.**>',
    ...     subject='Testing',
    ...     body='Hello, world!\\n',
    ...     content_type='plain',
    ...     extra_headers={'Approved': '*****@*****.**'})
    >>> print(message.as_string())  # doctest: +REPORT_UDIFF
    MIME-Version: 1.0
    Content-Type: text/plain; charset="us-ascii"
    Content-Transfer-Encoding: 7bit
    From: John <*****@*****.**>
    To: =?utf-8?b?zpbOtc+Nz4I=?= <*****@*****.**>
    Subject: Testing
    Approved: [email protected]
    <BLANKLINE>
    Hello, world!
    <BLANKLINE>
    """
    if config is None:
        config = _config.CONFIG
    if section not in config.sections():
        section = 'DEFAULT'
    encodings = [
        x.strip() for x in config.get(section, 'encodings').split(',')
    ]

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = _parseaddr(sender)
    recipient_list = []
    for recipient_name, recipient_addr in _getaddresses([recipient]):
        recipient_encoding = guess_encoding(recipient_name, encodings)
        recipient_name = str(
            _Header(recipient_name, recipient_encoding).encode())
        recipient_addr.encode('ascii')
        recipient_list.append(_formataddr((recipient_name, recipient_addr)))

    sender_encoding = guess_encoding(sender_name, encodings)
    recipient_encoding = guess_encoding(recipient_name, encodings)
    subject_encoding = guess_encoding(subject, encodings)
    body_encoding = guess_encoding(body, encodings)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(_Header(sender_name, sender_encoding).encode())

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    message = _MIMEText(body, content_type, body_encoding)
    message['From'] = _formataddr((sender_name, sender_addr))
    message['To'] = ', '.join(recipient_list)
    message['Subject'] = _Header(subject, subject_encoding)
    if config.getboolean(section, 'use-8bit'):
        del message['Content-Transfer-Encoding']
        charset = _Charset(body_encoding)
        charset.body_encoding = _email_encoders.encode_7or8bit
        message.set_payload(body, charset=charset)
    if extra_headers:
        for key, value in extra_headers.items():
            encoding = guess_encoding(value, encodings)
            message[key] = _Header(value, encoding)
    return message
def Header(name):  # noqa
    return _Header(name, 'utf-8').encode()