當前位置: 首頁>>代碼示例>>Python>>正文


Python utils.getaddresses方法代碼示例

本文整理匯總了Python中email.utils.getaddresses方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.getaddresses方法的具體用法?Python utils.getaddresses怎麽用?Python utils.getaddresses使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在email.utils的用法示例。


在下文中一共展示了utils.getaddresses方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: addr_header_encode

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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() 
開發者ID:Pagure,項目名稱:pagure,代碼行數:23,代碼來源:git_multimail_upstream.py

示例2: forbid_multi_line_headers

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:20,代碼來源:message.py

示例3: forbid_multi_line_headers

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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 
開發者ID:quantmind,項目名稱:lux,代碼行數:20,代碼來源:message.py

示例4: parse_email_addresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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) 
開發者ID:ikvk,項目名稱:imap_tools,代碼行數:20,代碼來源:utils.py

示例5: clean_addresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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 
開發者ID:ofa,項目名稱:connect,代碼行數:23,代碼來源:utils.py

示例6: set_recipients

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def set_recipients(self, name, value):
        self.unset_all(name)
        for pair in getaddresses([value]):
            self.add(name, formataddr(pair)) 
開發者ID:Pagure,項目名稱:pagure,代碼行數:6,代碼來源:git_multimail_upstream.py

示例7: send

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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) 
開發者ID:Pagure,項目名稱:pagure,代碼行數:33,代碼來源:git_multimail_upstream.py

示例8: test_getaddresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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')]) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:8,代碼來源:test_email_renamed.py

示例9: test_getaddresses_nasty

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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')]) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:11,代碼來源:test_email_renamed.py

示例10: test_getaddresses_embedded_comment

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
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') 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:7,代碼來源:test_email_renamed.py

示例11: addrs

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def addrs(raw_addrs):
    items = []

    # TODO remove the cleaner!
    # raw_addrs = [clean_string(convert_encoded(s.lower()),[EXPR_OPTS['fix_utf8'],(r'\t', ';'), (r'\n', ';') ]) for s in raw_addrs]
    # arr = [clean_string(s.lower(), [EXPR_OPTS['fix_utf8'], (r'\t', ';'), (r'\n', ';') ]) for s in arr]
    utf8_addrs = [convert_encoded(raw_addr) for raw_addr in raw_addrs]

    for name, addr in getaddresses(utf8_addrs):
        if u'@' in addr:
            items.append(addr)
        elif u'@' in name:
            items.append(name)
    return  ([clean_string(s.lower(), [(r'\'', u'')]) for s in items], utf8_addrs) 
開發者ID:Sotera,項目名稱:pst-extraction,代碼行數:16,代碼來源:email_extract_json_unicode.py

示例12: format_addresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def format_addresses(addrs, remove_empty=False):
    if isinstance(addrs, basestring):
        addrs = [addrs]

    pairs = getaddresses(addrs)
    if remove_empty:
        pairs = [(x, y) for (x, y) in pairs if x or y]

    # FIXME: Use encoding after getaddresses
    return ", ".join(map(formataddr, pairs)) 
開發者ID:abusesa,項目名稱:abusehelper,代碼行數:12,代碼來源:mailer.py

示例13: clean_recipients

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def clean_recipients(recipients):
    recipients = [addr for (name, addr) in getaddresses(recipients)]
    return filter(None, (x.strip() for x in recipients)) 
開發者ID:abusesa,項目名稱:abusehelper,代碼行數:5,代碼來源:mailer.py

示例14: addresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def addresses(txt):
    addrs = [
        {
            'addr': a[1].lower(),
            'name': address_name(a),
            'title': '"{}" <{}>'.format(*a) if a[0] else a[1],
            'hash': hashlib.md5(a[1].strip().lower().encode()).hexdigest(),
        } for a in getaddresses([txt])
    ]
    return addrs 
開發者ID:naspeh,項目名稱:mailur,代碼行數:12,代碼來源:message.py

示例15: _get_addresses

# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def _get_addresses(self, address_data, retain_name=False):
        """
        Takes RFC-compliant email addresses in both terse (email only)
        and verbose (name + email) forms and returns a list of
        email address strings

        (TODO: breaking change that returns a tuple of (name, email) per string)
        """
        if retain_name:
            raise NotImplementedError(
                "Not yet implemented, but will need client-code changes too"
            )

        # We trust than an email address contains an "@" after
        # email.utils.getaddresses has done the hard work. If we wanted
        # to we could use a regex to check for greater email validity

        # NB: getaddresses expects a list, so ensure we feed it appropriately
        if isinstance(address_data, str):
            if "[" not in address_data:
                # Definitely turn these into a list
                # NB: this is pretty assumptive, but still prob OK
                address_data = [address_data]

        output = [x[1] for x in getaddresses(address_data) if "@" in x[1]]
        return output 
開發者ID:yunojuno-archive,項目名稱:django-inbound-email,代碼行數:28,代碼來源:sendgrid.py


注:本文中的email.utils.getaddresses方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。