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


Python Charset.header_encode方法代碼示例

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


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

示例1: format

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
    def format(self, events, encoding="utf-8"):
        parts = list()
        data = templates.Template.format(self, parts, events)
        parsed = message_from_string(data.encode(encoding))

        charset = Charset(encoding)
        charset.header_encoding = QP

        msg = MIMEMultipart()
        msg.set_charset(charset)
        for key, value in msg.items():
            del parsed[key]
        for key, value in parsed.items():
            msg[key] = value

        for encoded in ["Subject", "Comment"]:
            if encoded not in msg:
                continue
            value = charset.header_encode(msg[encoded])
            del msg[encoded]
            msg[encoded] = value

        del msg["Content-Transfer-Encoding"]
        msg["Content-Transfer-Encoding"] = "7bit"

        msg.attach(MIMEText(parsed.get_payload(), "plain", encoding))
        for part in parts:
            msg.attach(part)
        return msg
開發者ID:ics-forks,項目名稱:abusehelper,代碼行數:31,代碼來源:mailer.py

示例2: formataddr

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
def formataddr(pair, charset='utf-8'):
    """The inverse of parseaddr(), this takes a 2-tuple of the form
    (realname, email_address) and returns the string value suitable
    for an RFC 2822 From, To or Cc header.

    If the first element of pair is false, then the second element is
    returned unmodified.

    Optional charset if given is the character set that is used to encode
    realname in case realname is not ASCII safe.  Can be an instance of str or
    a Charset-like object which has a header_encode method.  Default is
    'utf-8'.
    """
    name, address = pair
    # The address MUST (per RFC) be ascii, so throw a UnicodeError if it isn't.
    address.encode('ascii')
    if name:
        try:
            name.encode('ascii')
        except UnicodeEncodeError:
            if isinstance(charset, str):
                charset = Charset(charset)
            encoded_name = charset.header_encode(name)
            return "%s <%s>" % (encoded_name, address)
        else:
            quotes = ''
            if specialsre.search(name):
                quotes = '"'
            name = escapesre.sub(r'\\\g<0>', name)
            return '%s%s%s <%s>' % (quotes, name, quotes, address)
    return address
開發者ID:Patsy63,項目名稱:python-3.3,代碼行數:33,代碼來源:utils.py

示例3: format

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
    def format(self, events, encoding="utf-8"):
        from email import message_from_string
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText
        from email.charset import Charset, QP
        from email.utils import formatdate, make_msgid

        parts = list()
        data = templates.Template.format(self, parts, events)
        parsed = message_from_string(data.encode(encoding))

        charset = Charset(encoding)
        charset.header_encoding = QP

        msg = MIMEMultipart()
        msg.set_charset(charset)
        for key, value in msg.items():
            del parsed[key]
        for key, value in parsed.items():
            msg[key] = value

        for encoded in ["Subject", "Comment"]:
            if encoded not in msg:
                continue
            value = charset.header_encode(msg[encoded])
            del msg[encoded]
            msg[encoded] = value

        del msg['Content-Transfer-Encoding']
        msg['Content-Transfer-Encoding'] = '7bit'

        msg.attach(MIMEText(parsed.get_payload(), "plain", encoding))
        for part in parts:
            msg.attach(part)
        return msg
開發者ID:Rafiot,項目名稱:Abusehelper,代碼行數:37,代碼來源:mailer.py

示例4: send

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
    def send(self, subject, recipients, sender=None, attach=None,
             html=None, text=None, template=None, **kwargs):
        """
        Отправка самосборного письма.
        Ссылки на картинке в статике превращаются в аттачменты. Текст правильно кодируется, чтобы
        избежать багов с переносом строки в Flask-Mail

        recipients - список
        attach - вложения, словарь имя-путь
        template - можно указать имя шаблона без расширения

        """

        sender = sender or self.default_sender

        if template:
            html, text = render_email(template, **kwargs)

        recipients_str = self._contact_list(recipients)

        charset = Charset(input_charset='utf-8')

        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = charset.header_encode(subject)
        msgRoot['From'] = self._contact(sender)
        msgRoot['To'] = recipients_str
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        msgRoot.set_charset('utf-8')

        msgAlternative = MIMEMultipart(_subtype='alternative')
        msgAlternative.set_charset("utf-8")
        msgRoot.attach(msgAlternative)

        msgText = MIMEText(_text=text, _subtype='plain', _charset='utf-8')
        msgAlternative.attach(msgText)

        html, images = self._extract_statics(html)
        self._attach_images(msgRoot, images)
        if attach:
            self._attach_images(msgRoot, attach)

        msgHtml = MIMEText(_text=html, _subtype='html', _charset='utf-8')
        msgAlternative.attach(msgHtml)

        if self.mail_enabled:
            with smtplib.SMTP(host=self.mail_server, port=self.mail_port) as smtp:
                smtp.sendmail(
                    self._address(sender),
                    [self._address(r) for r in recipients], 
                    msgRoot.as_string()
                )
開發者ID:neoden,項目名稱:typo,代碼行數:53,代碼來源:mail.py

示例5: formataddr

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
def formataddr(pair, charset='utf-8'):
    (name, address) = pair
    address.encode('ascii')
    if name:
        try:
            name.encode('ascii')
        except UnicodeEncodeError:
            if isinstance(charset, str):
                charset = Charset(charset)
            encoded_name = charset.header_encode(name)
            return '%s <%s>' % (encoded_name, address)
        quotes = ''
        if specialsre.search(name):
            quotes = '"'
        name = escapesre.sub('\\\\\\g<0>', name)
        return '%s%s%s <%s>' % (quotes, name, quotes, address)
    return address
開發者ID:johndpope,項目名稱:sims4-ai-engine,代碼行數:19,代碼來源:utils.py

示例6: encode_address

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
 def encode_address(addr):
     name, email = parseaddr(addr)
     charset = Charset(guess_charset(name))
     encoded_name = charset.header_encode(name)
     return formataddr((encoded_name, email))
開發者ID:yhlam,項目名稱:gmail,代碼行數:7,代碼來源:draft.py

示例7: send_email

# 需要導入模塊: from email.charset import Charset [as 別名]
# 或者: from email.charset.Charset import header_encode [as 別名]
def send_email(subject, recipients, sender=None, attach=None,
               html_body=None, text_body=None, template=None, **kwargs):
    """
    Отправка самосборного письма.
    Ссылки на картинке в статике превращаются в аттачменты. Текст правильно кодируется, чтобы
    избежать багов с переносом строки в Flask-Mail

    recipients - Список
    attach - Вложения, словарь имя-путь
    template - Имя шаблона без расширения. Будет искатся пара файлов <template>.html и <template>.txt

    """

    if sender is None:
        cfg = current_app.config
        sender = cfg.get('MAIL_DEFAULT_SENDER', '[email protected]{}'.format(cfg.get('SERVER_NAME', 'example.com')))

    if template:
        html_body, text_body = render_email(template, **kwargs)

    recipients_str = contact_list(recipients)

    charset = Charset(input_charset='utf-8')

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = charset.header_encode(subject)
    msgRoot['From'] = contact(sender)
    msgRoot['To'] = recipients_str
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    msgRoot.set_charset('utf-8')

    msgAlternative = MIMEMultipart(_subtype='alternative')
    msgAlternative.set_charset("utf-8")
    msgRoot.attach(msgAlternative)

    msgText = MIMEText(_text=text_body, _subtype='plain', _charset='utf-8')
    msgAlternative.attach(msgText)

    html, images = extract_statics(html_body)
    attach_images(msgRoot, images)
    if attach:
        attach_images(msgRoot, attach)

    msgHtml = MIMEText(_text=html, _subtype='html', _charset='utf-8')
    msgAlternative.attach(msgHtml)

    if current_app.config['MAIL_ENABLED']:
        with smtplib.SMTP(
                host=current_app.config['MAIL_SERVER'], 
                port=current_app.config['MAIL_PORT']) as smtp:
            try:
                smtp.sendmail(
                    address(sender),
                    [address(r) for r in recipients],
                    msgRoot.as_string()
                )
                if current_app.config.get('DEBUG'):
                    print('=== MAIL FROM "%s" TO "%s"' % (address(sender), repr([address(r) for r in recipients])))
                    print(msgRoot.as_string())
            except smtplib.SMTPRecipientsRefused:
                print('smtplib.SMTPRecipientsRefused: %s' % repr(recipients))
開發者ID:uisky,項目名稱:flask-fish,代碼行數:63,代碼來源:mail.py


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