当前位置: 首页>>代码示例>>Python>>正文


Python i18n.set_translation函数代码示例

本文整理汇总了Python中Mailman.i18n.set_translation函数的典型用法代码示例。如果您正苦于以下问题:Python set_translation函数的具体用法?Python set_translation怎么用?Python set_translation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了set_translation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sendProbe

 def sendProbe(self, member, msg):
     listname = self.real_name
     # Put together the substitution dictionary.
     d = {
         "listname": listname,
         "address": member,
         "optionsurl": self.GetOptionsURL(member, absolute=True),
         "owneraddr": self.GetOwnerEmail(),
     }
     text = Utils.maketext("probe.txt", d, lang=self.getMemberLanguage(member), mlist=self)
     # Calculate the VERP'd sender address for bounce processing of the
     # probe message.
     token = self.pend_new(Pending.PROBE_BOUNCE, member, msg)
     probedict = {"bounces": self.internal_name() + "-bounces", "token": token}
     probeaddr = "%[email protected]%s" % ((mm_cfg.VERP_PROBE_FORMAT % probedict), self.host_name)
     # Calculate the Subject header, in the member's preferred language
     ulang = self.getMemberLanguage(member)
     otrans = i18n.get_translation()
     i18n.set_language(ulang)
     try:
         subject = _("%(listname)s mailing list probe message")
     finally:
         i18n.set_translation(otrans)
     outer = Message.UserNotification(member, probeaddr, subject, lang=ulang)
     outer.set_type("multipart/mixed")
     text = MIMEText(text, _charset=Utils.GetCharSet(ulang))
     outer.attach(text)
     outer.attach(MIMEMessage(msg))
     # Turn off further VERP'ing in the final delivery step.  We set
     # probe_token for the OutgoingRunner to more easily handling local
     # rejects of probe messages.
     outer.send(self, envsender=probeaddr, verp=False, probe_token=token)
开发者ID:jurov,项目名称:gnu-mailman,代码行数:32,代码来源:Deliverer.py

示例2: html_foot

    def html_foot(self):
        # avoid i18n side-effects
        mlist = self.maillist
        otrans = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        # Convenience
        def quotetime(s):
            return html_quote(i18n.ctime(s), self.lang)
        try:
            d = {"lastdate": quotetime(self.lastdate),
                 "archivedate": quotetime(self.archivedate),
                 "listinfo": mlist.GetScriptURL('listinfo', absolute=1),
                 "version": self.version,
                 "listname": html_quote(mlist.real_name, self.lang),
                 }
            i = {"thread": _("thread"),
                 "subject": _("subject"),
                 "author": _("author"),
                 "date": _("date")
                 }
        finally:
            i18n.set_translation(otrans)

        for t in i.keys():
            cap = t[0].upper() + t[1:]
            if self.type == cap:
                d["%s_ref" % (t)] = ""
            else:
                d["%s_ref" % (t)] = ('<a href="%s.html#start">[ %s ]</a>'
                                     % (t, i[t]))
        return quick_maketext(
            'archidxfoot.html', d,
            mlist=mlist)
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:33,代码来源:HyperArch.py

示例3: __refuse

 def __refuse(self, request, recip, comment, origmsg=None, lang=None):
     # As this message is going to the requestor, try to set the language
     # to his/her language choice, if they are a member.  Otherwise use the
     # list's preferred language.
     realname = self.real_name
     if lang is None:
         lang = self.getMemberLanguage(recip)
     text = Utils.maketext(
         'refuse.txt',
         {'listname' : realname,
          'request'  : request,
          'reason'   : comment,
          'adminaddr': self.GetOwnerEmail(),
         }, lang=lang, mlist=self)
     otrans = i18n.get_translation()
     i18n.set_language(lang)
     try:
         # add in original message, but not wrap/filled
         if origmsg:
             text = NL.join(
                 [text,
                  '---------- ' + _('Original Message') + ' ----------',
                  str(origmsg)
                  ])
         subject = _('Request to mailing list %(realname)s rejected')
     finally:
         i18n.set_translation(otrans)
     msg = Message.UserNotification(recip, self.GetOwnerEmail(),
                                    subject, text, lang)
     msg.send(self)
开发者ID:bdraco,项目名称:mailman,代码行数:30,代码来源:ListAdmin.py

示例4: decode_headers

    def decode_headers(self):
        """MIME-decode headers.

        If the email, subject, or author attributes contain non-ASCII
        characters using the encoded-word syntax of RFC 2047, decoded versions
        of those attributes are placed in the self.decoded (a dictionary).

        If the list's charset differs from the header charset, an attempt is
        made to decode the headers as Unicode.  If that fails, they are left
        undecoded.
        """
        author = self.decode_charset(self.author)
        subject = self.decode_charset(self.subject)
        if author:
            self.decoded['author'] = author
            email = self.decode_charset(self.email)
            if email:
                self.decoded['email'] = email
        if subject:
            if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
                otrans = i18n.get_translation()
                try:
                    i18n.set_language(self._lang)
                    atmark = unicode(_(' at '), Utils.GetCharSet(self._lang))
                    subject = re.sub(r'([-+,.\w]+)@([-+.\w]+)',
                              '\g<1>' + atmark + '\g<2>', subject)
                finally:
                    i18n.set_translation(otrans)
            self.decoded['subject'] = subject
        self.decoded['stripped'] = self.strip_subject(subject or self.subject)
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:30,代码来源:HyperArch.py

示例5: as_html

    def as_html(self):
        """Different attributes that can be used when generating a html file from a template for the archives."""	
        d = self.__dict__.copy()
        # avoid i18n side-effects
        otrans = i18n.get_translation()
        i18n.set_language(self._lang)
        try:
            d["prev"], d["prev_wsubj"] = self._get_prev()
            d["next"], d["next_wsubj"] = self._get_next()

            d["email_html"] = self.quote(self.email)
            d["title"] = self.quote(self.subject)
            d["subject_html"] = self.quote(self.subject)
            # TK: These two _url variables are used to compose a response
            # from the archive web page.  So, ...
            # Possibly remove since not used??
            d["subject_url"] = url_quote('Re: ' + self.subject)
            d["in_reply_to_url"] = url_quote(self._message_id)
            if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
                # Point the mailto url back to the list
                author = re.sub('@', _(' at '), self.author)
                emailurl = self._mlist.GetListEmail()
            else:
                author = self.author
                emailurl = self.email
            d["author_html"] = self.quote(author)
            d["email_url"] = url_quote(emailurl)
            d["datestr_html"] = self.quote(i18n.ctime(int(self.date)))
            d["body"] = self._get_body()
            d['listurl'] = self._mlist.GetScriptURL('listinfo', absolute=1)
            d['listname'] = self._mlist.real_name
            d['encoding'] = ''
            try:
                # This should work after a couple of emails has been send and the thread 
                # address has been set, but to not get an error in the beginning the error 
                # is caught and an already existing address is provided. Is for dlists.
                d['thread_addr'] = self.thread_addr
                d['thread_addr_at'] = re.sub('@', _(' at '), self.thread_addr)
            except:
                d['thread_addr'] = d["email_url"]
                d['thread_addr_at'] = d["email_url"]
        finally:
            i18n.set_translation(otrans)

        charset = Utils.GetCharSet(self._lang)
        d["encoding"] = html_charset % charset

        self._add_decoded(d)
        return quick_maketext(
             'article.html', d,
             lang=self._lang, mlist=self._mlist)
开发者ID:jdk2588,项目名称:systers-gsoc10-membership,代码行数:51,代码来源:HyperArch.py

示例6: SendHostileSubscriptionNotice

    def SendHostileSubscriptionNotice(self, listname, address):
        # Some one was invited to one list but tried to confirm to a different
        # list.  We inform both list owners of the bogosity, but be careful
        # not to reveal too much information.
        selfname = self.internal_name()
        syslog("mischief", "%s was invited to %s but confirmed to %s", address, listname, selfname)
        # First send a notice to the attacked list
        msg = Message.OwnerNotification(
            self,
            _("Hostile subscription attempt detected"),
            Utils.wrap(
                _(
                    """%(address)s was invited to a different mailing
list, but in a deliberate malicious attempt they tried to confirm the
invitation to your list.  We just thought you'd like to know.  No further
action by you is required."""
                )
            ),
        )
        msg.send(self)
        # Now send a notice to the invitee list
        try:
            # Avoid import loops
            from Mailman.MailList import MailList

            mlist = MailList(listname, lock=False)
        except Errors.MMListError:
            # Oh well
            return
        otrans = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        try:
            msg = Message.OwnerNotification(
                mlist,
                _("Hostile subscription attempt detected"),
                Utils.wrap(
                    _(
                        """You invited %(address)s to your list, but in a
deliberate malicious attempt, they tried to confirm the invitation to a
different list.  We just thought you'd like to know.  No further action by you
is required."""
                    )
                ),
            )
            msg.send(mlist)
        finally:
            i18n.set_translation(otrans)
开发者ID:jurov,项目名称:gnu-mailman,代码行数:47,代码来源:Deliverer.py

示例7: _onefile

 def _onefile(self, msg, msgdata):
     # Do some common sanity checking on the message metadata.  It's got to
     # be destined for a particular mailing list.  This switchboard is used
     # to shunt off badly formatted messages.  We don't want to just trash
     # them because they may be fixable with human intervention.  Just get
     # them out of our site though.
     #
     # Find out which mailing list this message is destined for.
     listname = msgdata.get('listname')
     if not listname:
         listname = mm_cfg.MAILMAN_SITE_LIST
     mlist = self._open_list(listname)
     if not mlist:
         syslog('error',
                'Dequeuing message destined for missing list: %s',
                listname)
         self._shunt.enqueue(msg, msgdata)
         return
     # Now process this message, keeping track of any subprocesses that may
     # have been spawned.  We'll reap those later.
     #
     # We also want to set up the language context for this message.  The
     # context will be the preferred language for the user if a member of
     # the list, or the list's preferred language.  However, we must take
     # special care to reset the defaults, otherwise subsequent messages
     # may be translated incorrectly.  BAW: I'm not sure I like this
     # approach, but I can't think of anything better right now.
     otranslation = i18n.get_translation()
     sender = msg.get_sender()
     if mlist:
         lang = mlist.getMemberLanguage(sender)
     else:
         lang = mm_cfg.DEFAULT_SERVER_LANGUAGE
     i18n.set_language(lang)
     msgdata['lang'] = lang
     try:
         keepqueued = self._dispose(mlist, msg, msgdata)
     finally:
         i18n.set_translation(otranslation)
     # Keep tabs on any child processes that got spawned.
     kids = msgdata.get('_kids')
     if kids:
         self._kids.update(kids)
     if keepqueued:
         self._switchboard.enqueue(msg, msgdata)
开发者ID:EmilyDirsh,项目名称:Paperboy,代码行数:45,代码来源:Runner.py

示例8: html_TOC

    def html_TOC(self):
        mlist = self.maillist
        listname = mlist.internal_name()
        mbox = os.path.join(mlist.archive_dir()+'.mbox', listname+'.mbox')
        d = {"listname": mlist.real_name,
             "listinfo": mlist.GetScriptURL('listinfo', absolute=1),
             "fullarch": '../%s.mbox/%s.mbox' % (listname, listname),
             "size": sizeof(mbox, mlist.preferred_language),
             'meta': '',
             }
        # Avoid i18n side-effects
        otrans = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        try:
            if not self.archives:
                d["noarchive_msg"] = _(
                    '<P>Currently, there are no archives. </P>')
                d["archive_listing_start"] = ""
                d["archive_listing_end"] = ""
                d["archive_listing"] = ""
            else:
                d["noarchive_msg"] = ""
                d["archive_listing_start"] = quick_maketext(
                    'archliststart.html',
                    lang=mlist.preferred_language,
                    mlist=mlist)
                d["archive_listing_end"] = quick_maketext(
                    'archlistend.html',
                    mlist=mlist)

                accum = []
                for a in self.archives:
                    accum.append(self.html_TOC_entry(a))
                d["archive_listing"] = EMPTYSTRING.join(accum)
        finally:
            i18n.set_translation(otrans)
        # The TOC is always in the charset of the list's preferred language
        d['meta'] += html_charset % Utils.GetCharSet(mlist.preferred_language)
        # The site can disable public access to the mbox file.
        if mm_cfg.PUBLIC_MBOX:
            template = 'archtoc.html'
        else:
            template = 'archtocnombox.html'
        return quick_maketext(template, d, mlist=mlist)
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:44,代码来源:HyperArch.py

示例9: as_html

    def as_html(self):
        d = self.__dict__.copy()
        # avoid i18n side-effects
        otrans = i18n.get_translation()
        i18n.set_language(self._lang)
        try:
            d["prev"], d["prev_wsubj"] = self._get_prev()
            d["next"], d["next_wsubj"] = self._get_next()

            d["email_html"] = self.quote(self.email)
            d["title"] = self.quote(self.subject)
            d["subject_html"] = self.quote(self.subject)
            d["message_id"] = self.quote(self._message_id)
            # TK: These two _url variables are used to compose a response
            # from the archive web page.  So, ...
            d["subject_url"] = url_quote('Re: ' + self.subject)
            d["in_reply_to_url"] = url_quote(self._message_id)
            if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
                # Point the mailto url back to the list
                author = re.sub('@', _(' at '), self.author)
                emailurl = self._mlist.GetListEmail()
            else:
                author = self.author
                emailurl = self.email
            d["author_html"] = self.quote(author)
            d["email_url"] = url_quote(emailurl)
            d["datestr_html"] = self.quote(i18n.ctime(int(self.date)))
            d["body"] = self._get_body()
            d['listurl'] = self._mlist.GetScriptURL('listinfo', absolute=1)
            d['listname'] = self._mlist.real_name
            d['encoding'] = ''
        finally:
            i18n.set_translation(otrans)

        charset = Utils.GetCharSet(self._lang)
        d["encoding"] = html_charset % charset

        self._add_decoded(d)
        return quick_maketext(
             'article.html', d,
             lang=self._lang, mlist=self._mlist)
开发者ID:fumiyas,项目名称:mailman-ja-utf8-debian,代码行数:41,代码来源:HyperArch.py

示例10: html_head

    def html_head(self):
        # avoid i18n side-effects
        mlist = self.maillist
        otrans = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        # Convenience
        def quotetime(s):
            return html_quote(i18n.ctime(s), self.lang)
        try:
            d = {"listname": html_quote(mlist.real_name, self.lang),
                 "archtype": self.type,
                 "archive":  self.volNameToDesc(self.archive),
                 "listinfo": mlist.GetScriptURL('listinfo', absolute=1),
                 "firstdate": quotetime(self.firstdate),
                 "lastdate": quotetime(self.lastdate),
                 "size": self.size,
                 }
            i = {"thread": _("thread"),
                 "subject": _("subject"),
                 "author": _("author"),
                 "date": _("date"),
                 }
        finally:
            i18n.set_translation(otrans)

        for t in i.keys():
            cap = t[0].upper() + t[1:]
            if self.type == cap:
                d["%s_ref" % (t)] = ""
                d["archtype"] = i[t]
            else:
                d["%s_ref" % (t)] = ('<a href="%s.html#start">[ %s ]</a>'
                                     % (t, i[t]))
        if self.charset:
            d["encoding"] = html_charset % self.charset
        else:
            d["encoding"] = ""
        return quick_maketext(
            'archidxhead.html', d,
            mlist=mlist)
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:40,代码来源:HyperArch.py

示例11: send_digests

def send_digests(mlist, mboxfp):
    # Set the digest volume and time
    if mlist.digest_last_sent_at:
        bump = False
        # See if we should bump the digest volume number
        timetup = time.localtime(mlist.digest_last_sent_at)
        now = time.localtime(time.time())
        freq = mlist.digest_volume_frequency
        if freq == 0 and timetup[0] < now[0]:
            # Yearly
            bump = True
        elif freq == 1 and timetup[1] <> now[1]:
            # Monthly, but we take a cheap way to calculate this.  We assume
            # that the clock isn't going to be reset backwards.
            bump = True
        elif freq == 2 and (timetup[1] % 4 <> now[1] % 4):
            # Quarterly, same caveat
            bump = True
        elif freq == 3:
            # Once again, take a cheap way of calculating this
            weeknum_last = int(time.strftime('%W', timetup))
            weeknum_now = int(time.strftime('%W', now))
            if weeknum_now > weeknum_last or timetup[0] > now[0]:
                bump = True
        elif freq == 4 and timetup[7] <> now[7]:
            # Daily
            bump = True
        if bump:
            mlist.bump_digest_volume()
    mlist.digest_last_sent_at = time.time()
    # Wrapper around actually digest crafter to set up the language context
    # properly.  All digests are translated to the list's preferred language.
    otranslation = i18n.get_translation()
    i18n.set_language(mlist.preferred_language)
    try:
        send_i18n_digests(mlist, mboxfp)
    finally:
        i18n.set_translation(otranslation)
开发者ID:fumiyas,项目名称:mailman-ja-utf8-debian,代码行数:38,代码来源:ToDigest.py

示例12: as_text

 def as_text(self):
     d = self.__dict__.copy()
     # We need to guarantee a valid From_ line, even if there are
     # bososities in the headers.
     if not d.get('fromdate', '').strip():
         d['fromdate'] = time.ctime(time.time())
     if not d.get('email', '').strip():
         d['email'] = '[email protected]'
     if not d.get('datestr', '').strip():
         d['datestr'] = time.ctime(time.time())
     #
     headers = ['From %(email)s  %(fromdate)s',
              'From: %(email)s (%(author)s)',
              'Date: %(datestr)s',
              'Subject: %(subject)s']
     if d['_in_reply_to']:
         headers.append('In-Reply-To: %(_in_reply_to)s')
     if d['_references']:
         headers.append('References: %(_references)s')
     if d['_message_id']:
         headers.append('Message-ID: %(_message_id)s')
     body = EMPTYSTRING.join(self.body)
     cset = Utils.GetCharSet(self._lang)
     # Coerce the body to Unicode and replace any invalid characters.
     if not isinstance(body, types.UnicodeType):
         body = unicode(body, cset, 'replace')
     if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
         otrans = i18n.get_translation()
         try:
             i18n.set_language(self._lang)
             atmark = unicode(_(' at '), cset)
             body = re.sub(r'([-+,.\w]+)@([-+.\w]+)',
                           '\g<1>' + atmark + '\g<2>', body)
         finally:
             i18n.set_translation(otrans)
     # Return body to character set of article.
     body = body.encode(cset, 'replace')
     return NL.join(headers) % d + '\n\n' + body + '\n'
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:38,代码来源:HyperArch.py

示例13: hold_for_approval

def hold_for_approval(mlist, msg, msgdata, exc):
    # BAW: This should really be tied into the email confirmation system so
    # that the message can be approved or denied via email as well as the
    # web.
    #
    # XXX We use the weird type(type) construct below because in Python 2.1,
    # type is a function not a type and so can't be used as the second
    # argument in isinstance().  However, in Python 2.5, exceptions are
    # new-style classes and so are not of ClassType.
    if isinstance(exc, ClassType) or isinstance(exc, type(type)):
        # Go ahead and instantiate it now.
        exc = exc()
    listname = mlist.real_name
    sender = msgdata.get('sender', msg.get_sender())
    usersubject = msg.get('subject')
    charset = Utils.GetCharSet(mlist.preferred_language)
    if usersubject:
        usersubject = Utils.oneline(usersubject, charset)
    else:
        usersubject = _('(no subject)')
    message_id = msg.get('message-id', 'n/a')
    owneraddr = mlist.GetOwnerEmail()
    adminaddr = mlist.GetBouncesEmail()
    requestaddr = mlist.GetRequestEmail()
    # We need to send both the reason and the rejection notice through the
    # translator again, because of the games we play above
    reason = Utils.wrap(exc.reason_notice())
    msgdata['rejection_notice'] = Utils.wrap(exc.rejection_notice(mlist))
    id = mlist.HoldMessage(msg, reason, msgdata)
    # Now we need to craft and send a message to the list admin so they can
    # deal with the held message.
    d = {'listname'   : listname,
         'hostname'   : mlist.host_name,
         'reason'     : _(reason),
         'sender'     : sender,
         'subject'    : usersubject,
         'admindb_url': mlist.GetScriptURL('admindb', absolute=1),
         }
    # We may want to send a notification to the original sender too
    fromusenet = msgdata.get('fromusenet')
    # Since we're sending two messages, which may potentially be in different
    # languages (the user's preferred and the list's preferred for the admin),
    # we need to play some i18n games here.  Since the current language
    # context ought to be set up for the user, let's craft his message first.
    cookie = mlist.pend_new(Pending.HELD_MESSAGE, id)
    if not fromusenet and ackp(msg) and mlist.respond_to_post_requests and \
           mlist.autorespondToSender(sender, mlist.getMemberLanguage(sender)):
        # Get a confirmation cookie
        d['confirmurl'] = '%s/%s' % (mlist.GetScriptURL('confirm', absolute=1),
                                     cookie)
        lang = msgdata.get('lang', mlist.getMemberLanguage(sender))
        subject = _('Your message to %(listname)s awaits moderator approval')
        text = Utils.maketext('postheld.txt', d, lang=lang, mlist=mlist)
        nmsg = Message.UserNotification(sender, owneraddr, subject, text, lang)
        nmsg.send(mlist)
    # Now the message for the list owners.  Be sure to include the list
    # moderators in this message.  This one should appear to come from
    # <list>-owner since we really don't need to do bounce processing on it.
    if mlist.admin_immed_notify:
        # Now let's temporarily set the language context to that which the
        # admin is expecting.
        otranslation = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        try:
            lang = mlist.preferred_language
            charset = Utils.GetCharSet(lang)
            # We need to regenerate or re-translate a few values in d
            d['reason'] = _(reason)
            d['subject'] = usersubject
            # craft the admin notification message and deliver it
            subject = _('%(listname)s post from %(sender)s requires approval')
            nmsg = Message.UserNotification(owneraddr, owneraddr, subject,
                                            lang=lang)
            nmsg.set_type('multipart/mixed')
            text = MIMEText(
                Utils.maketext('postauth.txt', d, raw=1, mlist=mlist),
                _charset=charset)
            dmsg = MIMEText(Utils.wrap(_("""\
If you reply to this message, keeping the Subject: header intact, Mailman will
discard the held message.  Do this if the message is spam.  If you reply to
this message and include an Approved: header with the list password in it, the
message will be approved for posting to the list.  The Approved: header can
also appear in the first line of the body of the reply.""")),
                            _charset=Utils.GetCharSet(lang))
            dmsg['Subject'] = 'confirm ' + cookie
            dmsg['Sender'] = requestaddr
            dmsg['From'] = requestaddr
            dmsg['Date'] = email.Utils.formatdate(localtime=True)
            dmsg['Message-ID'] = Utils.unique_message_id(mlist)
            nmsg.attach(text)
            nmsg.attach(MIMEMessage(msg))
            nmsg.attach(MIMEMessage(dmsg))
            nmsg.send(mlist, **{'tomoderators': 1})
        finally:
            i18n.set_translation(otranslation)
    # Log the held message
    syslog('vette', '%s post from %s held, message-id=%s: %s',
           listname, sender, message_id, reason)
    # raise the specific MessageHeld exception to exit out of the message
    # delivery pipeline
#.........这里部分代码省略.........
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:101,代码来源:Hold.py

示例14: process

def process(mlist, msg, msgdata):
    # Set the "X-Ack: no" header if noack flag is set.
    if msgdata.get('noack'):
        change_header('X-Ack', 'no', mlist, msg, msgdata)
    # Because we're going to modify various important headers in the email
    # message, we want to save some of the information in the msgdata
    # dictionary for later.  Specifically, the sender header will get waxed,
    # but we need it for the Acknowledge module later.
    # We may have already saved it; if so, don't clobber it here.
    if 'original_sender' not in msgdata:
        msgdata['original_sender'] = msg.get_sender()
    # VirginRunner sets _fasttrack for internally crafted messages.
    fasttrack = msgdata.get('_fasttrack')
    if not msgdata.get('isdigest') and not fasttrack:
        try:
            prefix_subject(mlist, msg, msgdata)
        except (UnicodeError, ValueError):
            # TK: Sometimes subject header is not MIME encoded for 8bit
            # simply abort prefixing.
            pass
    # Mark message so we know we've been here, but leave any existing
    # X-BeenThere's intact.
    change_header('X-BeenThere', mlist.GetListEmail(),
                  mlist, msg, msgdata, delete=False)
    # Add Precedence: and other useful headers.  None of these are standard
    # and finding information on some of them are fairly difficult.  Some are
    # just common practice, and we'll add more here as they become necessary.
    # Good places to look are:
    #
    # http://www.dsv.su.se/~jpalme/ietf/jp-ietf-home.html
    # http://www.faqs.org/rfcs/rfc2076.html
    #
    # None of these headers are added if they already exist.  BAW: some
    # consider the advertising of this a security breach.  I.e. if there are
    # known exploits in a particular version of Mailman and we know a site is
    # using such an old version, they may be vulnerable.  It's too easy to
    # edit the code to add a configuration variable to handle this.
    change_header('X-Mailman-Version', mm_cfg.VERSION,
                  mlist, msg, msgdata, repl=False)
    # We set "Precedence: list" because this is the recommendation from the
    # sendmail docs, the most authoritative source of this header's semantics.
    change_header('Precedence', 'list',
                  mlist, msg, msgdata, repl=False)
    # Do we change the from so the list takes ownership of the email
    if (msgdata.get('from_is_list') or mlist.from_is_list) and not fasttrack:
        # Be as robust as possible here.
        faddrs = getaddresses(msg.get_all('from', []))
        # Strip the nulls and bad emails.
        faddrs = [x for x in faddrs if x[1].find('@') > 0]
        if len(faddrs) == 1:
            realname, email = o_from = faddrs[0]
        else:
            # No From: or multiple addresses.  Just punt and take
            # the get_sender result.
            realname = ''
            email = msgdata['original_sender']
            o_from = (realname, email)
        if not realname:
            if mlist.isMember(email):
                realname = mlist.getMemberName(email) or email
            else:
                realname = email
        # Remove domain from realname if it looks like an email address
        realname = re.sub(r'@([^ .]+\.)+[^ .]+$', '---', realname)
        # Make a display name and RFC 2047 encode it if necessary.  This is
        # difficult and kludgy. If the realname came from From: it should be
        # ascii or RFC 2047 encoded. If it came from the list, it should be
        # in the charset of the list's preferred language or possibly unicode.
        # if it's from the email address, it should be ascii. In any case,
        # make it a unicode.
        if isinstance(realname, unicode):
            urn = realname
        else:
            rn, cs = ch_oneline(realname)
            urn = unicode(rn, cs, errors='replace')
        # likewise, the list's real_name which should be ascii, but use the
        # charset of the list's preferred_language which should be a superset.
        lcs = Utils.GetCharSet(mlist.preferred_language)
        ulrn = unicode(mlist.real_name, lcs, errors='replace')
        # get translated 'via' with dummy replacements
        realname = '%(realname)s'
        lrn = '%(lrn)s'
        # We want the i18n context to be the list's preferred_language.  It
        # could be the poster's.
        otrans = i18n.get_translation()
        i18n.set_language(mlist.preferred_language)
        via = _('%(realname)s via %(lrn)s')
        i18n.set_translation(otrans)
        uvia = unicode(via, lcs, errors='replace')
        # Replace the dummy replacements.
        uvia = re.sub(u'%\(lrn\)s', ulrn, re.sub(u'%\(realname\)s', urn, uvia))
        # And get an RFC 2047 encoded header string.
        dn = str(Header(uvia, lcs))
        change_header('From',
                      formataddr((dn, mlist.GetListEmail())),
                      mlist, msg, msgdata)
    else:
        # Use this as a flag
        o_from = None
    # Reply-To: munging.  Do not do this if the message is "fast tracked",
#.........这里部分代码省略.........
开发者ID:fumiyas,项目名称:mailman-ja-utf8-debian,代码行数:101,代码来源:CookHeaders.py

示例15: __init__

    def __init__(self, message=None, sequence=0, keepHeaders=[],
                       lang=mm_cfg.DEFAULT_SERVER_LANGUAGE, mlist=None):
        self.__super_init(message, sequence, keepHeaders)
        self.prev = None
        self.next = None
        # Trim Re: from the subject line
        i = 0
        while i != -1:
            result = REpat.match(self.subject)
            if result:
                i = result.end(0)
                self.subject = self.subject[i:]
            else:
                i = -1
        # Useful to keep around
        self._lang = lang
        self._mlist = mlist

        if mm_cfg.ARCHIVER_OBSCURES_EMAILADDRS:
            # Avoid i18n side-effects.  Note that the language for this
            # article (for this list) could be different from the site-wide
            # preferred language, so we need to ensure no side-effects will
            # occur.  Think what happens when executing bin/arch.
            otrans = i18n.get_translation()
            try:
                i18n.set_language(lang)
                if self.author == self.email:
                    self.author = self.email = re.sub('@', _(' at '),
                                                      self.email)
                else:
                    self.email = re.sub('@', _(' at '), self.email)
            finally:
                i18n.set_translation(otrans)

        # Snag the content-* headers.  RFC 1521 states that their values are
        # case insensitive.
        ctype = message.get('Content-Type', 'text/plain')
        cenc = message.get('Content-Transfer-Encoding', '')
        self.ctype = ctype.lower()
        self.cenc = cenc.lower()
        self.decoded = {}
        cset = Utils.GetCharSet(mlist.preferred_language)
        cset_out = Charset(cset).output_charset or cset
        if isinstance(cset_out, unicode):
            # email 3.0.1 (python 2.4) doesn't like unicode
            cset_out = cset_out.encode('us-ascii')
        charset = message.get_content_charset(cset_out)
        if charset:
            charset = charset.lower().strip()
            if charset[0]=='"' and charset[-1]=='"':
                charset = charset[1:-1]
            if charset[0]=="'" and charset[-1]=="'":
                charset = charset[1:-1]
            try:
                body = message.get_payload(decode=True)
            except binascii.Error:
                body = None
            if body and charset != Utils.GetCharSet(self._lang):
                # decode body
                try:
                    body = unicode(body, charset)
                except (UnicodeError, LookupError):
                    body = None
            if body:
                self.body = [l + "\n" for l in body.splitlines()]

        self.decode_headers()
开发者ID:EdLeafe,项目名称:mailman_config,代码行数:67,代码来源:HyperArch.py


注:本文中的Mailman.i18n.set_translation函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。