本文整理汇总了Python中email.header.Header方法的典型用法代码示例。如果您正苦于以下问题:Python header.Header方法的具体用法?Python header.Header怎么用?Python header.Header使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.header
的用法示例。
在下文中一共展示了header.Header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _bind_write_headers
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def _bind_write_headers(msg):
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp)
return _write_headers
示例2: addr_header_encode
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [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()
示例3: send_mail
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def send_mail(to_email,message):
# 定义邮件发送
# Define send_mail() function
smtp_host = 'smtp.xxx.com'
# 发件箱服务器
# Outbox Server
from_email = 'from_email@xxx.com'
# 发件邮箱
# from_email
passwd = 'xxxxxx'
# 发件邮箱密码
# from_email_password
msg = MIMEText(message,'plain','utf-8')
msg['Subject'] = Header(u'Email Subject','utf-8').encode()
# 邮件主题
# Email Subject
smtp_server = smtplib.SMTP(smtp_host,25)
# 发件服务器端口
# Outbox Server Port
smtp_server.login(from_email,passwd)
smtp_server.sendmail(from_email,[to_email],msg.as_string())
smtp_server.quit()
示例4: forbid_multi_line_headers
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [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
示例5: sanitize_address
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def sanitize_address(addr, encoding):
if isinstance(addr, six.string_types):
addr = parseaddr(force_text(addr))
nm, addr = addr
# This try-except clause is needed on Python 3 < 3.2.4
# http://bugs.python.org/issue14291
try:
nm = Header(nm, encoding).encode()
except UnicodeEncodeError:
nm = Header(nm, 'utf-8').encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN
if '@' in addr:
localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((nm, addr))
示例6: __init__
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
"""Create the generator for message flattening.
outfp is the output file-like object for writing the message to. It
must have a write() method.
Optional mangle_from_ is a flag that, when True (the default), escapes
From_ lines in the body of the message by putting a `>' in front of
them.
Optional maxheaderlen specifies the longest length for a non-continued
header. When a header line is longer (in characters, with tabs
expanded to 8 spaces) than maxheaderlen, the header will split as
defined in the Header class. Set maxheaderlen to zero to disable
header wrapping. The default is 78, as recommended (but not required)
by RFC 2822.
"""
self._fp = outfp
self._mangle_from_ = mangle_from_
self._maxheaderlen = maxheaderlen
示例7: send_message
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def send_message(self, to_user, title, body, **kwargs):
if self.ssl:
smtp_client = smtplib.SMTP_SSL()
else:
smtp_client = smtplib.SMTP()
smtp_client.connect(zvt_env['smtp_host'], zvt_env['smtp_port'])
smtp_client.login(zvt_env['email_username'], zvt_env['email_password'])
msg = MIMEMultipart('alternative')
msg['Subject'] = Header(title).encode()
msg['From'] = "{} <{}>".format(Header('zvt').encode(), zvt_env['email_username'])
if type(to_user) is list:
msg['To'] = ", ".join(to_user)
else:
msg['To'] = to_user
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()
plain_text = MIMEText(body, _subtype='plain', _charset='UTF-8')
msg.attach(plain_text)
try:
smtp_client.sendmail(zvt_env['email_username'], to_user, msg.as_string())
except Exception as e:
self.logger.exception('send email failed', e)
示例8: send_email
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def send_email(msg_to, msg_subject, msg_body, msg_from=None,
smtp_server='localhost', envelope_from=None,
headers={}):
if not msg_from:
msg_from = app.config['EMAIL_FROM']
if not envelope_from:
envelope_from = parseaddr(msg_from)[1]
msg = MIMEText(msg_body)
msg['Subject'] = Header(msg_subject)
msg['From'] = msg_from
msg['To'] = msg_to
msg['Date'] = formatdate()
msg['Message-ID'] = make_msgid()
msg['Errors-To'] = envelope_from
if request:
msg['X-Submission-IP'] = request.remote_addr
s = smtplib.SMTP(smtp_server)
s.sendmail(envelope_from, msg_to, msg.as_string())
s.close()
示例9: test_get_param
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def test_get_param(self):
eq = self.assertEqual
msg = email.message_from_string(
"X-Header: foo=one; bar=two; baz=three\n")
eq(msg.get_param('bar', header='x-header'), 'two')
eq(msg.get_param('quuz', header='x-header'), None)
eq(msg.get_param('quuz'), None)
msg = email.message_from_string(
'X-Header: foo; bar="one"; baz=two\n')
eq(msg.get_param('foo', header='x-header'), '')
eq(msg.get_param('bar', header='x-header'), 'one')
eq(msg.get_param('baz', header='x-header'), 'two')
# XXX: We are not RFC-2045 compliant! We cannot parse:
# msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
# msg.get_param("weird")
# yet.
示例10: test_splitting_multiple_long_lines
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def test_splitting_multiple_long_lines(self):
eq = self.ndiffAssertEqual
hstr = """\
from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
"""
h = Header(hstr, continuation_ws='\t')
eq(h.encode(), """\
from babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)""")
示例11: test_long_lines_with_different_header
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def test_long_lines_with_different_header(self):
eq = self.ndiffAssertEqual
h = """\
List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
msg = Message()
msg['List'] = h
msg['List'] = Header(h, header_name='List')
self.ndiffAssertEqual(msg.as_string(), """\
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
<mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
""")
# Test mangling of "From " lines in the body of a message
示例12: test__all__
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def test__all__(self):
module = __import__('email')
# Can't use sorted() here due to Python 2.3 compatibility
all = module.__all__[:]
all.sort()
self.assertEqual(all, [
# Old names
'Charset', 'Encoders', 'Errors', 'Generator',
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
'MIMENonMultipart', 'MIMEText', 'Message',
'Parser', 'Utils', 'base64MIME',
# new names
'base64mime', 'charset', 'encoders', 'errors', 'generator',
'header', 'iterators', 'message', 'message_from_file',
'message_from_string', 'mime', 'parser',
'quopriMIME', 'quoprimime', 'utils',
])
示例13: _format_addr
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def _format_addr(s):
"""
parse the email sender and receiver, Chinese encode and support
:param s: eg. 'name <email@website.com>, name2 <email2@web2.com>'
"""
name, addr = parseaddr(s)
return formataddr((Header(name, "utf-8").encode(), addr))
示例14: send
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def send(self):
if len(self.attachment_list) == 0:
self.msg = MIMEText(self.content, self.mail_type, self.charset)
else:
self.msg = MIMEMultipart()
self.msg.attach(MIMEText(self.content, self.mail_type, self.charset))
for attachment in self.attachment_list:
self.msg.attach(attachment)
self.msg['Subject'] =Header(self.subject,self.charset)
self.msg['From'] = self.server_from_addr
self.msg['To'] = ",".join(self.to_addr)
if self.cc_addr:
self.msg['cc'] = ",".join(self.cc_addr)
if self.bcc_addr:
self.msg['bcc'] = ",".join(self.bcc_addr)
#send
for a in range(self.try_time):
try:
if self.smtp_port == 25:
server = smtplib.SMTP(self.smtp_server, self.smtp_port,timeout=self.time_out)
else:
server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port,timeout=self.time_out)
#server.set_debuglevel(1)
server.login(self.smtp_user,self.smtp_pass)
server.sendmail(self.server_from_addr,self.server_to_addrs,self.msg.as_string())
server.quit()
break
except Exception as e:
print(e)
示例15: header_encode
# 需要导入模块: from email import header [as 别名]
# 或者: from email.header import Header [as 别名]
def header_encode(text, header_name=None):
"""Encode and line-wrap the value of an email header field."""
# Convert to unicode, if required.
if not isinstance(text, unicode):
text = unicode(text, "utf-8")
if is_ascii(text):
charset = "ascii"
else:
charset = "utf-8"
return Header(
text, header_name=header_name, charset=Charset(charset)
).encode()