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


Python email.utils方法代碼示例

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


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

示例1: _encode_field

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def _encode_field(self, name, value):
        self._log(DEBUG1, '_FormDataPart._encode_field: %s %s',
                  type(name), type(value))
        if not _rfc2231_encode:
            s = '%s="%s"' % (name, value)
            self._log(DEBUG1, '_FormDataPart._encode_field: %s %s',
                      type(s), s)
            if _isunicode(s):
                s = s.encode('utf-8')
                self._log(DEBUG1, '_FormDataPart._encode_field: %s %s',
                          type(s), s)
            return s

        if not [ch for ch in '\r\n\\' if ch in value]:
            try:
                return ('%s="%s"' % (name, value)).encode('ascii')
            except UnicodeEncodeError:
                self._log(DEBUG1, 'UnicodeEncodeError 3.x')
            except UnicodeDecodeError:  # 2.x
                self._log(DEBUG1, 'UnicodeDecodeError 2.x')
        # RFC 2231
        value = email.utils.encode_rfc2231(value, 'utf-8')
        return ('%s*=%s' % (name, value)).encode('ascii') 
開發者ID:PaloAltoNetworks,項目名稱:terraform-templates,代碼行數:25,代碼來源:wfapi.py

示例2: dateToUTCstr

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def dateToUTCstr(str_date):
    # this fails to parse timezones out of formats like
    # Tue, 17 Jun 2010 08:33:51 EDT
    # so it will assume the local timezone for those cases

    try:
        dt = dateutil.parser.parse(str_date)
    except (TypeError, ValueError) as e:
        # print u"Failed to parse date with dateutil, using email utils: date={}".format(str_date)
        parsed_dt = parsedate_tz(str_date)
        # Make an arbitrary tz info object name can be anything NSTZ "Newman Seconds Time Zone"
        nstz_info = dateutil.tz.tzoffset("NSTZ",parsed_dt[9])
        dt= datetime.datetime(*parsed_dt[:6], tzinfo=nstz_info)


    if not dt.tzinfo:
        print "WARNING:  Failed to parse timezone defaulting to UTC for Date: {}".format(str_date)
        dt = dt.replace(tzinfo=dateutil.tz.tzutc())

    dt_tz = dt.astimezone(dateutil.tz.tzutc())
    time_str =  dt_tz.strftime('%Y-%m-%dT%H:%M:%S')
    # print u"Parsed date={} ====> {}".format(str_date, time_str)

    return time_str 
開發者ID:Sotera,項目名稱:pst-extraction,代碼行數:26,代碼來源:email_extract_json_unicode.py

示例3: generate_email_files

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def generate_email_files(msg):
    counter = 1
    upload_date = time.mktime(email.utils.parsedate(msg["Date"]))
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1

        data = part.get_payload(decode=True)
        if parse_pathname(filename).ext == '.zip':
            for zipfn, zipdata, zipdt in generate_zip_files(data):
                yield zipfn, zipdata, zipdt
        else:
            yield filename, data, upload_date 
開發者ID:century-arcade,項目名稱:xd,代碼行數:26,代碼來源:12-parse-email.py

示例4: getmailaddresses

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def getmailaddresses(self, prop):
        """retrieve From:, To: and Cc: addresses"""
        addrs=email.utils.getaddresses(self.msg.get_all(prop, []))
        for i, (name, addr) in enumerate(addrs):
            if not name and addr:
                # only one string! Is it the address or is it the name ?
                # use the same for both and see later
                name=addr

            try:
                # address must be ascii only
                addr=addr.encode('ascii')
            except UnicodeError:
                addr=''
            else:
                # address must match adress regex
                if not email_address_re.match(addr.decode("utf-8")):
                    addr=''
            if not isinstance(addr, str):
                # Python 2 imaplib returns a bytearray,
                # Python 3 imaplib returns a str.
                addrs[i]=(self.getmailheader(name), addr.decode("utf-8"))
        return addrs 
開發者ID:polo2ro,項目名稱:imapbox,代碼行數:25,代碼來源:message.py

示例5: get_addr_header

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def get_addr_header(self, header_name):
        """Get a list of the first addresses from this header."""
        values = list()
        for value in self.get_decoded_header(header_name):
            for dummy, addr in email.utils.getaddresses([value]):
                if addr:
                    values.append(addr)
                    break
        return values 
開發者ID:SpamExperts,項目名稱:OrangeAssassin,代碼行數:11,代碼來源:message.py

示例6: _get_last_chromium_modification

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def _get_last_chromium_modification():
    """Returns the last modification date of the chromium-browser-official tar file"""
    with _get_requests_session() as session:
        response = session.head(
            'https://storage.googleapis.com/chromium-browser-official/chromium-{}.tar.xz'.format(
                get_chromium_version()))
        response.raise_for_status()
        return email.utils.parsedate_to_datetime(response.headers['Last-Modified']) 
開發者ID:Eloston,項目名稱:ungoogled-chromium,代碼行數:10,代碼來源:validate_patches.py

示例7: _get_gitiles_git_log_date

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def _get_gitiles_git_log_date(log_entry):
    """Helper for _get_gitiles_git_log_date"""
    return email.utils.parsedate_to_datetime(log_entry['committer']['time']) 
開發者ID:Eloston,項目名稱:ungoogled-chromium,代碼行數:5,代碼來源:validate_patches.py

示例8: open_local_file

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def open_local_file(self, req):
        import email.utils
        import mimetypes
        host = req.host
        filename = req.selector
        localfile = url2pathname(filename)
        try:
            stats = os.stat(localfile)
            size = stats.st_size
            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
            mtype = mimetypes.guess_type(filename)[0]
            headers = email.message_from_string(
                'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
                (mtype or 'text/plain', size, modified))
            if host:
                host, port = splitport(host)
            if not host or \
                (not port and _safe_gethostbyname(host) in self.get_names()):
                if host:
                    origurl = 'file://' + host + filename
                else:
                    origurl = 'file://' + filename
                return addinfourl(open(localfile, 'rb'), headers, origurl)
        except OSError as exp:
            # users shouldn't expect OSErrors coming from urlopen()
            raise URLError(exp)
        raise URLError('file not on local host') 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:29,代碼來源:request.py

示例9: _send_to_sendmail

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def _send_to_sendmail(self, message, email_addresses, cc=None, bcc=None,
                          sender=None):
        msg = email.mime.text.MIMEText(base.handle_encoding(message),
                                       'html' if self.html else 'plain')
        msg['Subject'] = base.handle_encoding(self._get_summary())
        msg['From'] = _get_sender(sender)
        msg['To'] = ', '.join(email_addresses)
        # We could pass the priority in the 'Importance' header, but
        # since nobody pays attention to that (and we can't even set
        # that header when sending from appengine), we just use the
        # fact it's embedded in the subject line.
        if cc:
            if not isinstance(cc, six.string_types):
                cc = ', '.join(cc)
            msg['Cc'] = cc
        if bcc:
            if not isinstance(bcc, six.string_types):
                bcc = ', '.join(bcc)
            msg['Bcc'] = bcc

        # I think sendmail wants just email addresses, so extract
        # them in case the user specified "Name <email>".
        to_emails = [email.utils.parseaddr(a) for a in email_addresses]
        to_emails = [email_addr for (_, email_addr) in to_emails]

        s = smtplib.SMTP('localhost')
        s.sendmail('no-reply@khanacademy.org', to_emails, msg.as_string())
        s.quit() 
開發者ID:Khan,項目名稱:alertlib,代碼行數:30,代碼來源:email.py

示例10: open_local_file

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def open_local_file(self, req):
        import email.utils
        import mimetypes
        host = req.host
        filename = req.selector
        localfile = url2pathname(filename)
        try:
            stats = os.stat(localfile)
            size = stats.st_size
            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
            mtype = mimetypes.guess_type(filename)[0]
            headers = email.message_from_string(
                'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
                (mtype or 'text/plain', size, modified))
            if host:
                host, port = splitport(host)
            if not host or \
                (not port and _safe_gethostbyname(host) in self.get_names()):
                if host:
                    origurl = 'file://' + host + filename
                else:
                    origurl = 'file://' + filename
                return addinfourl(open(localfile, 'rb'), headers, origurl)
        except OSError as exp:
            raise URLError(exp)
        raise URLError('file not on local host') 
開發者ID:CedricGuillemet,項目名稱:Imogen,代碼行數:28,代碼來源:request.py

示例11: parse_email

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def parse_email(message):
    """Parse email message"""
    msg = email.message_from_string(message)
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append(part.get_payload(decode=True).decode(
                part.get_content_charset() or 'utf-8'
            ))

    from_addr = email.utils.parseaddr(decode_header(msg['From']))
    to_addr = email.utils.getaddresses([decode_header(h) for h in msg.get_all('To')])
    subject = decode_header(msg['Subject'])
    return {'from': from_addr, 'to': to_addr, 'subject': subject, 'body': parts} 
開發者ID:xmikos,項目名稱:pyxolotl,代碼行數:16,代碼來源:email.py

示例12: parse_address

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def parse_address(addr_str):
    name, addr = email.utils.parseaddr(_parse_header(addr_str))
    return name, addr 
開發者ID:patchew-project,項目名稱:patchew,代碼行數:5,代碼來源:mbox.py

示例13: _get_addr_list

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def _get_addr_list(self, field, text):
        ret = []
        f = self._m.get_all(field, [])
        f = (_parse_header(x) for x in f)
        addrs = email.utils.getaddresses(f)
        for name, addr in addrs:
            name = name or addr
            if text:
                ret.append(_addr_fmt_text(name, addr))
            else:
                ret.append((name, addr))
        if text:
            ret = ", ".join(ret)
        return ret 
開發者ID:patchew-project,項目名稱:patchew,代碼行數:16,代碼來源:mbox.py

示例14: get_date

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def get_date(self, timestamp=False):
        tup = email.utils.parsedate_tz(self._m["date"])
        if tup:
            stamp = email.utils.mktime_tz(tup)
            if timestamp:
                return stamp
            return datetime.datetime.utcfromtimestamp(stamp) 
開發者ID:patchew-project,項目名稱:patchew,代碼行數:9,代碼來源:mbox.py

示例15: get_reviewed_by

# 需要導入模塊: import email [as 別名]
# 或者: from email import utils [as 別名]
def get_reviewed_by(self):
        """Try to find a "Reviewed-by:" line in message body"""
        prefix = "Reviewed-by:"
        r = self._find_line("^" + prefix + ".*>$")
        if r:
            return email.utils.parseaddr(r[len(prefix) :].strip())
        else:
            return None 
開發者ID:patchew-project,項目名稱:patchew,代碼行數:10,代碼來源:mbox.py


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