Python email.utils.parseaddr() Examples

The following are 30 code examples of email.utils.parseaddr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.utils , or try the search function .
Example #1
Source File: utils.py    From GerbLook with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def send_email(msg_to, msg_subject, msg_body, msg_from=None,
        smtp_server='localhost', envelope_from=None,
        headers={}):

  if not msg_from:
    msg_from = app.config['EMAIL_FROM']

  if not envelope_from:
    envelope_from = parseaddr(msg_from)[1]

  msg = MIMEText(msg_body)

  msg['Subject'] = Header(msg_subject)
  msg['From'] = msg_from
  msg['To'] = msg_to
  msg['Date'] = formatdate()
  msg['Message-ID'] = make_msgid()
  msg['Errors-To'] = envelope_from

  if request:
    msg['X-Submission-IP'] = request.remote_addr

  s = smtplib.SMTP(smtp_server)
  s.sendmail(envelope_from, msg_to, msg.as_string())
  s.close() 
Example #2
Source File: test_email.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_parseaddr_preserves_quoted_pairs_in_addresses(self):
        # issue 10005.  Note that in the third test the second pair of
        # backslashes is not actually a quoted pair because it is not inside a
        # comment or quoted string: the address being parsed has a quoted
        # string containing a quoted backslash, followed by 'example' and two
        # backslashes, followed by another quoted string containing a space and
        # the word 'example'.  parseaddr copies those two backslashes
        # literally.  Per rfc5322 this is not technically correct since a \ may
        # not appear in an address outside of a quoted string.  It is probably
        # a sensible Postel interpretation, though.
        eq = self.assertEqual
        eq(utils.parseaddr('""example" example"@example.com'),
          ('', '""example" example"@example.com'))
        eq(utils.parseaddr('"\\"example\\" example"@example.com'),
          ('', '"\\"example\\" example"@example.com'))
        eq(utils.parseaddr('"\\\\"example\\\\" example"@example.com'),
          ('', '"\\\\"example\\\\" example"@example.com')) 
Example #3
Source File: types.py    From parsec-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, email: str, label: str):
        # TODO: how to check the email  easily ?
        if not isinstance(email, str) or not 0 < _bytes_size(email) < 255:
            raise ValueError("Invalid email address")

        if not isinstance(label, str) or not 0 < _bytes_size(label) < 255:
            raise ValueError("Invalid label")

        parsed_label, parsed_email = parseaddr(str(self))
        if parsed_email != email:
            raise ValueError("Invalid email address")
        if parsed_label != label:
            raise ValueError("Invalid label")

        # No need to call super().__init__ given namedtuple set attributes during __new__
        super().__init__() 
Example #4
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                value = self._idna_encode(value)
                warnings.warn(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "idna. Support for passing unicode strings (aka U-label) "
                    "will be removed in a future version.",
                    utils.DeprecatedIn21,
                    stacklevel=2,
                )
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value 
Example #5
Source File: flask_mail.py    From flask-unchained with MIT License 6 votes vote down vote up
def sanitize_address(addr, encoding='utf-8'):
    if isinstance(addr, str):
        addr = parseaddr(force_text(addr))
    nm, addr = addr

    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            try:
                localpart = Header(localpart, encoding).encode()
            except UnicodeEncodeError:
                localpart = Header(localpart, 'utf-8').encode()
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #6
Source File: message.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, six.string_types):
        addr = parseaddr(force_text(addr))
    nm, addr = addr
    # This try-except clause is needed on Python 3 < 3.2.4
    # http://bugs.python.org/issue14291
    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #7
Source File: verifier.py    From email-verifier with MIT License 6 votes vote down vote up
def _parse_address(self, email) -> Address:
        """
        Parses the email address provided and splits it 
        into username and domain.

        Returns a named tuple Address
        """
        name, addr = parseaddr(email)
        if not addr:
            raise EmailFormatError(f"email does not contain address: {email}")
        try:
            domain = addr.split('@')[-1]
            username = addr.split('@')[:-1][0]
        except IndexError:
            raise EmailFormatError(f"address provided is invalid: {email}")
        return Address(name, addr, username, domain) 
Example #8
Source File: general_name.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(value, six.text_type):
            raise TypeError("value must be a unicode string")

        name, address = parseaddr(value)
        parts = address.split(u"@")
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")
        elif len(parts) == 1:
            # Single label email name. This is valid for local delivery.
            # No IDNA encoding needed since there is no domain component.
            encoded = address.encode("ascii")
        else:
            # A normal email of the form user@domain.com. Let's attempt to
            # encode the domain component and reconstruct the address.
            encoded = parts[0].encode("ascii") + b"@" + idna.encode(parts[1])

        self._value = value
        self._encoded = encoded 
Example #9
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                value = self._idna_encode(value)
                warnings.warn(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "idna. Support for passing unicode strings (aka U-label) "
                    "will be removed in a future version.",
                    utils.PersistentlyDeprecated2017,
                    stacklevel=2,
                )
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value 
Example #10
Source File: email.py    From ACE with Apache License 2.0 6 votes vote down vote up
def normalize_email_address(email_address):
    """Returns a normalized version of email address.  Returns None if the address cannot be parsed."""
    name, address = parseaddr(email_address)
    if address is None:
        return None

    address = address.strip()

    while address and address.startswith('<'):
        address = address[1:]

    while address and address.endswith('>'):
        address = address[:-1]

    if not address:
        return None

    return address.lower() 
Example #11
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                value = self._idna_encode(value)
                warnings.warn(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "idna. Support for passing unicode strings (aka U-label) "
                    "will be removed in a future version.",
                    utils.PersistentlyDeprecated2017,
                    stacklevel=2,
                )
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value 
Example #12
Source File: message.py    From lux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, str):
        addr = parseaddr(addr)
    nm, addr = addr
    nm = Header(nm, encoding).encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #13
Source File: general_name.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                value = self._idna_encode(value)
                warnings.warn(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "idna. Support for passing unicode strings (aka U-label) "
                    " will be removed in a future version.",
                    utils.DeprecatedIn21,
                    stacklevel=2,
                )
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value 
Example #14
Source File: general_name.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def __init__(self, value):
        if isinstance(value, six.text_type):
            try:
                value.encode("ascii")
            except UnicodeEncodeError:
                value = self._idna_encode(value)
                warnings.warn(
                    "RFC822Name values should be passed as an A-label string. "
                    "This means unicode characters should be encoded via "
                    "idna. Support for passing unicode strings (aka U-label) "
                    "will be removed in a future version.",
                    utils.PersistentlyDeprecated2017,
                    stacklevel=2,
                )
        else:
            raise TypeError("value must be string")

        name, address = parseaddr(value)
        if name or not address:
            # parseaddr has found a name (e.g. Name <email>) or the entire
            # value is an empty string.
            raise ValueError("Invalid rfc822name value")

        self._value = value 
Example #15
Source File: smtp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def quoteaddr(addr):
    """
    Turn an email address, possibly with realname part etc, into
    a form suitable for and SMTP envelope.
    """

    if isinstance(addr, Address):
        return b'<' + bytes(addr) + b'>'

    if isinstance(addr, bytes):
        addr = addr.decode('ascii')

    res = parseaddr(addr)

    if res == (None, None):
        # It didn't parse, use it as-is
        return  b'<' + bytes(addr) + b'>'
    else:
        return  b'<' + res[1].encode('ascii') + b'>' 
Example #16
Source File: utils.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def validate_address(address):
    """
    Validate C{address} as defined in RFC 2822.

    :param address: The address to be validated.
    :type address: str

    @return: A valid address.
    @rtype: str

    @raise smtp.SMTPBadRcpt: Raised if C{address} is invalid.
    """
    leap_assert_type(address, str)
    # in the following, the address is parsed as described in RFC 2822 and
    # ('', '') is returned if the parse fails.
    _, address = parseaddr(address)
    if address == '':
        raise smtp.SMTPBadRcpt(address)
    return address

#
# String manipulation
# 
Example #17
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, six.string_types):
        addr = parseaddr(force_text(addr))
    nm, addr = addr
    # This try-except clause is needed on Python 3 < 3.2.4
    # http://bugs.python.org/issue14291
    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #18
Source File: test_models.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_email_notification_reply_to_has_thread_id(self):
        user = VerifiedUserFactory()
        user2 = VerifiedUserFactory()
        group = GroupFactory(members=[user, user2])
        conversation = Conversation.objects.get_or_create_for_target(group)
        mail.outbox = []

        with execute_scheduled_tasks_immediately():
            message = ConversationMessage.objects.create(author=user, conversation=conversation, content='asdf')

        reply_to = parseaddr(mail.outbox[0].reply_to[0])[1]
        local_part = reply_to.split('@')[0]
        conversation_id, user_id, thread_id = parse_local_part(local_part)
        self.assertEqual(conversation_id, conversation.id)
        self.assertEqual(user_id, user2.id)
        self.assertEqual(thread_id, message.id) 
Example #19
Source File: backends.py    From django-mailjet with MIT License 6 votes vote down vote up
def _parse_recipients(self, message, recipients):
        rcpts = []
        recipient_vars = getattr(message, 'recipient_vars', {})

        for addr in recipients:
            rcpt = {}
            to_name, to_email = parseaddr(sanitize_address(addr, message.encoding))

            if to_name:
                rcpt['Name'] = to_name
            if to_email:
                rcpt['Email'] = to_email

            if recipient_vars.get(addr):
                rcpt['Vars'] = recipient_vars.get(addr)

            rcpts.append(rcpt)
        return rcpts 
Example #20
Source File: email_utils.py    From app with MIT License 6 votes vote down vote up
def parseaddr_unicode(addr) -> (str, str):
    """Like parseaddr but return name in unicode instead of in RFC 2047 format
    '=?UTF-8?B?TmjGoW4gTmd1eeG7hW4=?= <abcd@gmail.com>' -> ('Nhơn Nguyễn', "abcd@gmail.com")
    """
    name, email = parseaddr(addr)
    email = email.strip().lower()
    if name:
        name = name.strip()
        decoded_string, charset = decode_header(name)[0]
        if charset is not None:
            try:
                name = decoded_string.decode(charset)
            except UnicodeDecodeError:
                LOG.warning("Cannot decode addr name %s", name)
                name = ""
        else:
            name = decoded_string

    return name, email 
Example #21
Source File: admin.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean(self):
        if 'document_type' not in self.cleaned_data:
            self.add_error('document_type', 'document_type should be selected')
            return super().clean()

        dt = self.cleaned_data['document_type']
        fields = self.cleaned_data['user_fields']
        cc = DocumentNotificationSubscription.get_addrs(self.cleaned_data.get('recipients_cc'))

        if cc:
            bad_addrrs = {addr for addr in cc if parseaddr(addr)[1] != addr}
            if bad_addrrs:
                self.add_error('recipients_cc', 'Invalid emails in CC: {0}'.format(bad_addrrs))

        wrong_fields = list()
        for field in fields.all():  # type: DocumentField
            if field.document_type_id != dt.pk:
                wrong_fields.append(field)

        if wrong_fields:
            self.add_error('document_fields',
                           'Document fields should be owned by the specified document type.\n'
                           'The following fields do not match:\n'
                           '{wrong_fields}'.format(wrong_fields=';\n'.join([f.long_code for f in wrong_fields])))

        return super().clean() 
Example #22
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_escape_dump(self):
        self.assertEqual(
            utils.formataddr(('A (Very) Silly Person', 'person@dom.ain')),
            r'"A (Very) Silly Person" <person@dom.ain>')
        self.assertEqual(
            utils.parseaddr(r'"A \(Very\) Silly Person" <person@dom.ain>'),
            ('A (Very) Silly Person', 'person@dom.ain'))
        a = r'A \(Special\) Person'
        b = 'person@dom.ain'
        self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b)) 
Example #23
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_escape_backslashes(self):
        self.assertEqual(
            utils.formataddr(('Arthur \Backslash\ Foobar', 'person@dom.ain')),
            r'"Arthur \\Backslash\\ Foobar" <person@dom.ain>')
        a = r'Arthur \Backslash\ Foobar'
        b = 'person@dom.ain'
        self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b)) 
Example #24
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_multiline_from_comment(self):
        x = """\
Foo
\tBar <foo@example.com>"""
        self.assertEqual(utils.parseaddr(x), ('Foo Bar', 'foo@example.com')) 
Example #25
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_parseaddr_empty(self):
        self.assertEqual(utils.parseaddr('<>'), ('', ''))
        self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') 
Example #26
Source File: email_with_mako.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name), addr)) 
Example #27
Source File: general_name.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _idna_encode(self, value):
        idna = _lazy_import_idna()
        _, address = parseaddr(value)
        parts = address.split(u"@")
        return parts[0] + "@" + idna.encode(parts[1]).decode("ascii") 
Example #28
Source File: mailgun.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
            params = request.POST
            timestamp = params.get('timestamp', '')
            token = params.get('token', '')
            signature = params.get('signature', '')

            logger.debug('Received request: %s', params)

            if signature != hmac.new(key=utf8bytes(settings.MAILGUN_ACCESS_KEY),
                                     msg=utf8bytes('%s%s' % (timestamp, token)), digestmod=hashlib.sha256).hexdigest():
                logger.info('Rejected request: signature: %s, timestamp: %s, token: %s', signature, timestamp, token)
                raise PermissionDenied()
            _, sender = parseaddr(params.get('from'))
            if not sender:
                logger.info('Rejected invalid sender: %s', params.get('from'))
                return HttpResponse(status=406)
            try:
                user = User.objects.get(email__iexact=sender)
            except (User.DoesNotExist, User.MultipleObjectsReturned):
                logger.info('Rejected unknown sender: %s: %s', sender, params.get('from'))
                return HttpResponse(status=406)
            try:
                registration = RegistrationProfile.objects.get(user=user)
            except RegistrationProfile.DoesNotExist:
                logger.info('Rejected sender without RegistrationProfile: %s: %s', sender, params.get('from'))
                return HttpResponse(status=406)
            if registration.activated:
                logger.info('Rejected activated sender: %s: %s', sender, params.get('from'))
                return HttpResponse(status=406)

            key = registration.activation_key
            if key in params.get('body-plain', '') or key in params.get('body-html', ''):
                if RegistrationProfile.objects.activate_user(key, get_current_site(request)):
                    logger.info('Activated sender: %s: %s', sender, params.get('from'))
                    return HttpResponse('Activated', status=200)
                logger.info('Failed to activate sender: %s: %s', sender, params.get('from'))
            else:
                logger.info('Activation key not found: %s: %s', sender, params.get('from'))
            return HttpResponse(status=406) 
Example #29
Source File: mail.py    From Price-monitor with GNU General Public License v3.0 5 votes vote down vote up
def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr)) 
Example #30
Source File: health_metric.py    From royal-chaos with MIT License 5 votes vote down vote up
def format_addr(email):
    name, addr = parseaddr(email)
    return formataddr((Header(name, 'utf-8').encode(), addr))