本文整理汇总了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')
示例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
示例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
示例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
示例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
示例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'])
示例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'])
示例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')
示例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()
示例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')
示例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}
示例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
示例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
示例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)
示例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