Python email.utils.getaddresses() Examples

The following are 30 code examples of email.utils.getaddresses(). 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: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def addr_header_encode(text, header_name=None):
    """Encode and line-wrap the value of an email header field containing
    email addresses."""

    # Convert to unicode, if required.
    if not isinstance(text, unicode):
        text = unicode(text, "utf-8")

    text = ", ".join(
        formataddr((header_encode(name), emailaddr))
        for name, emailaddr in getaddresses([text])
    )

    if is_ascii(text):
        charset = "ascii"
    else:
        charset = "utf-8"

    return Header(
        text, header_name=header_name, charset=Charset(charset)
    ).encode() 
Example #2
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_text(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ADDRESS_HEADERS:
            val = ', '.join(sanitize_address(addr, encoding)
                for addr in getaddresses((val,)))
        else:
            val = Header(val, encoding).encode()
    else:
        if name.lower() == 'subject':
            val = Header(val).encode()
    return str(name), val 
Example #3
Source File: message.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_text(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ADDRESS_HEADERS:
            val = ', '.join(sanitize_address(addr, encoding)
                for addr in getaddresses((val,)))
        else:
            val = Header(val, encoding).encode()
    else:
        if name.lower() == 'subject':
            val = Header(val).encode()
    return str(name), val 
Example #4
Source File: utils.py    From imap_tools with Apache License 2.0 6 votes vote down vote up
def parse_email_addresses(raw_header: str) -> (dict,):
    """
    Parse email addresses from header
    :param raw_header: example: '=?UTF-8?B?0J7Qu9C1=?= <name@company.ru>,\r\n "\'\\"z, z\\"\'" <imap.tools@ya.ru>'
    :return: tuple(dict(name: str, email: str, full: str))
    """
    result = []
    for raw_name, email in getaddresses([raw_header]):
        name = decode_value(*decode_header(raw_name)[0]).strip()
        email = email.strip()
        if not (name or email):
            continue
        result.append({
            'email': email if '@' in email else '',
            'name': name,
            'full': '{} <{}>'.format(name, email) if name and email else name or email
        })
    return tuple(result) 
Example #5
Source File: utils.py    From connect with MIT License 6 votes vote down vote up
def clean_addresses(emails):
    """Takes a string of emails and returns a list of tuples of name/address
    pairs that are symanticly valid"""

    # Parse our string of emails, discarding invalid/illegal addresses
    valid_emails_list = address.parse_list(emails)

    # If no valid email addresses are found, return an empty list
    if not valid_emails_list:
        return []

    # If we have valid emails, use flanker's unicode address list creator to
    # give us something to pass to Python's email library's getaddresses
    valid_emails = valid_emails_list.to_unicode()

    # Return a list, in ('Name', 'email@dj.local')] form, the resulting emails
    email_list = getaddresses([valid_emails])

    # Lowercase all the email addresses in the list
    lowered_list = [(name, email.lower()) for name, email in email_list]
    return lowered_list 
Example #6
Source File: message.py    From lux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    if '\n' in val or '\r' in val:
        raise BadHeaderError(
            "Header values can't contain newlines (got %r for header %r)" %
            (val, name))
    try:
        val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ADDRESS_HEADERS:
            val = ', '.join(sanitize_address(addr, encoding)
                            for addr in getaddresses((val,)))
        else:
            val = Header(val, encoding).encode()
    else:
        if name.lower() == 'subject':
            val = Header(val).encode()
    return str(name), val 
Example #7
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #8
Source File: test_email_renamed.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #9
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #10
Source File: test_email_renamed.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_getaddresses_embedded_comment(self):
        """Test proper handling of a nested comment"""
        eq = self.assertEqual
        addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
        eq(addrs[0][1], 'foo@bar.com') 
Example #11
Source File: headers.py    From mailthon with MIT License 5 votes vote down vote up
def sender(self):
        """
        Returns the sender, respecting the Resent-*
        headers. In any case, prefer Sender over From,
        meaning that if Sender is present then From is
        ignored, as per the RFC.
        """
        to_fetch = (
            ['Resent-Sender', 'Resent-From'] if self.resent else
            ['Sender', 'From']
        )
        for item in to_fetch:
            if item in self:
                _, addr = getaddresses([self[item]])[0]
                return addr 
Example #12
Source File: headers.py    From mailthon with MIT License 5 votes vote down vote up
def receivers(self):
        """
        Returns a list of receivers, obtained from the
        To, Cc, and Bcc headers, respecting the Resent-*
        headers if the email was resent.
        """
        attrs = (
            ['Resent-To', 'Resent-Cc', 'Resent-Bcc'] if self.resent else
            ['To', 'Cc', 'Bcc']
        )
        addrs = (v for v in (self.get(k) for k in attrs) if v)
        return [addr for _, addr in getaddresses(addrs)] 
Example #13
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #14
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #15
Source File: test_email_renamed.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_getaddresses_embedded_comment(self):
        """Test proper handling of a nested comment"""
        eq = self.assertEqual
        addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
        eq(addrs[0][1], 'foo@bar.com') 
Example #16
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #17
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #18
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_embedded_comment(self):
        """Test proper handling of a nested comment"""
        eq = self.assertEqual
        addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
        eq(addrs[0][1], 'foo@bar.com') 
Example #19
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #20
Source File: test_email_renamed.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #21
Source File: validators.py    From modoboa-webmail with MIT License 5 votes vote down vote up
def __call__(self, value):
        value = force_text(value)
        addresses = getaddresses([value])
        [validate_email(email) for name, email in addresses if email] 
Example #22
Source File: test_email_renamed.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #23
Source File: test_email_renamed.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')]) 
Example #24
Source File: test_email_renamed.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses_embedded_comment(self):
        """Test proper handling of a nested comment"""
        eq = self.assertEqual
        addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
        eq(addrs[0][1], 'foo@bar.com') 
Example #25
Source File: test_email_renamed.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #26
Source File: test_email_renamed.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #27
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def set_recipients(self, name, value):
        self.unset_all(name)
        for pair in getaddresses([value]):
            self.add(name, formataddr(pair)) 
Example #28
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def send(self, lines, to_addrs):
        try:
            if self.username or self.password:
                self.smtp.login(self.username, self.password)
            msg = "".join(lines)
            # turn comma-separated list into Python list if needed.
            if is_string(to_addrs):
                to_addrs = [
                    email for (name, email) in getaddresses([to_addrs])
                ]
            self.smtp.sendmail(self.envelopesender, to_addrs, msg)
        except smtplib.SMTPResponseException:
            err = sys.exc_info()[1]
            self.environment.get_logger().error(
                "*** Error sending email ***\n"
                "*** Error %d: %s\n"
                % (err.smtp_code, bytes_to_str(err.smtp_error))
            )
            try:
                smtp = self.smtp
                # delete the field before quit() so that in case of
                # error, self.smtp is deleted anyway.
                del self.smtp
                smtp.quit()
            except:
                self.environment.get_logger().error(
                    "*** Error closing the SMTP connection ***\n"
                    "*** Exiting anyway ... ***\n"
                    "*** %s\n" % sys.exc_info()[1]
                )
            sys.exit(1) 
Example #29
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_getaddresses(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
                               'Bud Person <bperson@dom.ain>']),
           [('Al Person', 'aperson@dom.ain'),
            ('Bud Person', 'bperson@dom.ain')]) 
Example #30
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_getaddresses_nasty(self):
        eq = self.assertEqual
        eq(utils.getaddresses(['foo: ;']), [('', '')])
        eq(utils.getaddresses(
           ['[]*-- =~$']),
           [('', ''), ('', ''), ('', '*--')])
        eq(utils.getaddresses(
           ['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
           [('', ''), ('Jason R. Mastaler', 'jason@dom.ain')])