本文整理汇总了Python中email.Header.Header类的典型用法代码示例。如果您正苦于以下问题:Python Header类的具体用法?Python Header怎么用?Python Header使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Header类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_email
def send_email(self):
"""Sends the email
"""
properties = getUtility(IPropertiesTool)
mh = getToolByName(self.context, 'MailHost')
from_addr = properties.email_from_address
# prepare from address for header
header_from = Header(properties.email_from_name.decode('utf-8'),
'iso-8859-1')
header_from.append(u'<%s>' % from_addr.decode('utf-8'),
'iso-8859-1')
# Subject
subject = self.context.translate(self.get_subject())
header_subject = Header(unicode(subject), 'iso-8859-1')
html_body = self.render_template().encode('utf-8')
msg = MIMEText(html_body, 'html', 'utf-8')
msg['From'] = header_from
msg['Subject'] = header_subject
for rcpt in self.config.get_receivers():
msg['To'] = rcpt
mh.secureSend(msg, mto=rcpt, mfrom=from_addr, subject=subject)
示例2: encode_addresses
def encode_addresses(addresses, header_name = None):
"""
Unicode address headers are automatically encoded by
email.Header, but not correctly. The correct way is to put the
textual name inside quotes and the address inside brackets:
To: "=?utf-8?b?encoded" <[email protected]>
Each address in addrs may be a tuple of (name, address) or
just an address. Returns a tuple of (header, addrlist)
representing the encoded header text and the list of plain
text addresses.
"""
header = []
addrs = []
for addr in addresses:
if isinstance(addr, tuple):
(name, addr) = addr
try:
name = name.encode('ascii')
header.append('%s <%s>' % (name, addr))
except:
h = Header(name, charset = "utf-8", header_name = header_name)
header.append('"%s" <%s>' % (h.encode(), addr))
else:
header.append(addr)
addrs.append(addr)
return (", ".join(header), addrs)
示例3: __setitem__
def __setitem__(self, name, val):
"Forbids multi-line headers, to prevent header injection."
if "\n" in val or "\r" in val:
raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name)
if name == "Subject":
val = Header(val.encode(settings.MAIL_CHARSET, "replace"), settings.MAIL_CHARSET)
MIMEText.__setitem__(self, name, val)
示例4: forbid_multi_line_headers
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
encoding = encoding or settings.DEFAULT_CHARSET
val = force_unicode(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 = val.encode('ascii')
except UnicodeEncodeError:
if name.lower() in ('to', 'from', 'cc'):
result = []
for nm, addr in getaddresses((val,)):
nm = str(Header(nm.encode(encoding), encoding))
try:
addr = addr.encode('ascii')
except UnicodeEncodeError: # IDN
addr = str(Header(addr.encode(encoding), encoding))
result.append(formataddr((nm, addr)))
val = ', '.join(result)
else:
val = Header(val.encode(encoding), encoding)
else:
if name.lower() == 'subject':
val = Header(val)
return name, val
示例5: add_header
def add_header(self,key,value,immediate=False):
"""adds a header to the message. by default, headers will added when re-injecting the message back to postfix
if you set immediate=True the message source will be replaced immediately. Only set this to true if a header must be
visible to later plugins (eg. for spamassassin rules), otherwise, leave as False which is faster.
"""
if immediate:
val=unicode(value,errors='ignore') # is ignore the right thing to do here?
hdr=Header(val, header_name=key, continuation_ws=' ')
hdrline="%s: %s\n"%(key,hdr.encode())
src=hdrline+self.getSource()
self.set_source(src)
else:
self.addheaders[key]=value
示例6: sendDeleteNotifications
def sendDeleteNotifications(con, lang, project, category, relativeID, userID):
""" Send a notification in case of delete """
cursor = con.cursor()
# creating the list of recipients
query = """
SELECT mail
FROM Client
WHERE
subscription = True
AND allowed = True
AND project = %s"""
cursor.execute(query, (projectID(con, project), ))
recipients = []
for row in cursor.fetchall() :
recipients.append(row[0])
# get message content
query = """
SELECT name, lastMessageID
FROM Entry
WHERE relativeID = %s AND category = %s"""
categoryCode = {'bug' : 1, 'feature' : 2}
cursor.execute(query, (relativeID, categoryCode[category]))
row = cursor.fetchone()
title = row[0]
inReplyTo = row[1]
# user caracteristics (the one who deleted the entry)
query = """SELECT login, mail FROM Client WHERE id=%s"""
cursor.execute(query, (userID, ))
row = cursor.fetchone()
author = row[0]
authorMail = row[1]
# load template
mytemplate = Template(filename='templates/'+lang+'/mails/delete.mail', output_encoding='utf-8', default_filters=['decode.utf8'], input_encoding='utf-8')
text = mytemplate.render(creator = author)
category = category[0].upper()+category[1:].lower()
h = Header()
h.append(u'Re:', 'utf-8')
h.append(category, 'utf-8')
h.append(u'#'+str(relativeID)+u':', 'utf-8')
h.append(title, 'utf-8')
# make messageID
# no need to save it to the database : the entry will be deleted
messageID = make_msgid()
mail = {'From' : author + ' <' + authorMail + '>',
'To' : recipients,
'Subject' : h,
'Reply-To' : project + '@projects.naphtaline.net',
'Message-ID' : messageID,
'In-Reply-To' : inReplyTo,
'text' : text,
'files' : []}
send_mail(mail)
示例7: get_addr_line
def get_addr_line(name, addr):
'''Get the address line
:param str name: The display-name in the address.
:param str addr: The actual email address.
:returns: A correctly formatted mail header.
:rtype: str'''
# --=mpj17=-- In Python 3 just using formataddr, sans the Header,
# will work. This method should be removed.
unicodeName = to_unicode_or_bust(name)
headerName = Header(unicodeName, UTF8)
encodedName = headerName.encode()
retval = formataddr((encodedName, addr))
return retval
示例8: test_japanese_codecs
def test_japanese_codecs(self):
eq = self.ndiffAssertEqual
j = Charset("euc-jp")
g = Charset("iso-8859-1")
h = Header("Hello World!")
jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
ghello = 'Gr\xfc\xdf Gott!'
h.append(jhello, j)
h.append(ghello, g)
# BAW: This used to -- and maybe should -- fold the two iso-8859-1
# chunks into a single encoded word. However it doesn't violate the
# standard to have them as two encoded chunks and maybe it's
# reasonable <wink> for each .append() call to result in a separate
# encoded word.
eq(h.encode(), """\
Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?=
=?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=""")
eq(decode_header(h.encode()),
[('Hello World!', None),
('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
('Gr\xfc\xdf Gott!', 'iso-8859-1')])
long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
h = Header(long, j, header_name="Subject")
# test a very long header
enc = h.encode()
# TK: splitting point may differ by codec design and/or Header encoding
eq(enc , """\
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
=?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
# TK: full decode comparison
eq(h.__unicode__().encode('euc-jp'), long)
示例9: buildmsgsource
def buildmsgsource(suspect):
"""Build the message source with fuglu headers prepended"""
#we must prepend headers manually as we can't set a header order in email objects
origmsgtxt=suspect.getSource()
newheaders=""
for key in suspect.addheaders:
val=unicode(suspect.addheaders[key],errors='ignore') # is ignore the right thing to do here?
#self.logger.debug('Adding header %s : %s'%(key,val))
hdr=Header(val, header_name=key, continuation_ws=' ')
newheaders+="%s: %s\n"%(key,hdr.encode())
modifiedtext=newheaders+origmsgtxt
return modifiedtext
示例10: _encode_address_string
def _encode_address_string(text, charset):
"""Split the email into parts and use header encoding on the name
part if needed. We do this because the actual addresses need to be
ASCII with no encoding for most SMTP servers, but the non-address
parts should be encoded appropriately."""
header = Header()
name, addr = parseaddr(text)
try:
name.decode('us-ascii')
except UnicodeDecodeError:
if charset:
charset = Charset(charset)
name = charset.header_encode(name)
# We again replace rather than raise an error or pass an 8bit string
header.append(formataddr((name, addr)), errors='replace')
return header
示例11: main
def main(args):
msg1 = Message()
msg1.set_charset('iso-2022-jp')
msg1['From'] = Header(u'Yusuke Shinyama <[email protected]>', 'iso-2022-jp')
msg1['To'] = Header(u'きょうから明日です <[email protected]>', 'iso-2022-jp')
msg1['Subject'] = Header(u'ムーミン谷のみなさんへ', 'iso-2022-jp')
msg1['Date'] = 'Thu, 31 Aug 2004 03:06:09 +0900'
msg1.set_payload(u'その逆だ!'.encode('iso-2022-jp'), 'iso-2022-jp')
fp = file(args.pop(0), 'wb')
fp.write(msg1.as_string(0))
fp.close()
msg2 = MIMEMultipart()
msg2.set_charset('utf-8')
msg2['From'] = Header(u'えうすけ <[email protected]>', 'iso-2022-jp')
msg2['To'] = Header(u'だれでも <[email protected]>', 'utf-8')
msg2['Subject'] = Header(u'何を見てるんだい?', 'iso-2022-jp')
msg2['Date'] = 'Thu, 29 Feb 2004 19:23:34 +0500'
text1 = MIMEText(u'ああそうか、\nこれは夢なんだ。'.encode('utf-8'), 'plain', 'utf-8')
text2 = MIMEText(u'<html><body>\n<strong>HEY!</strong>\n<p>do you wanna feel unconfortably energetic?\n</body></html>', 'html')
h = Header(u'ふうばあ ばず', 'iso-2022-jp')
text2.add_header('Content-Disposition', 'attachment', filename=h.encode())
msg2.set_payload([text1, text2])
fp = file(args.pop(0), 'wb')
fp.write(msg2.as_string(0))
fp.close()
msg3 = MIMEMultipart()
msg3['From'] = '=?iso-2022-jp?b?Gy?= \xff\xaa\x88'
msg3['Subject'] = 'huh?'
msg3['Date'] = 'Tue, 25 Nov 2008 01:00:09 +0900'
parts = MIMEMultipart()
parts.set_payload([MIMEText('part1'), MIMEText('part2')])
msg4 = Message()
msg4.set_charset('iso-2022-jp')
msg4['From'] = Header(u'john doe <[email protected]>', 'iso-2022-jp')
msg4['To'] = Header(u'どこだって? <[email protected]>', 'iso-2022-jp')
msg4['Subject'] = Header(u'その先の日本へ', 'iso-2022-jp')
msg4['Date'] = 'Sun, 31 Aug 2008 12:20:33 +0900'
msg4.set_payload(u'ししかばう゛ー'.encode('iso-2022-jp'), 'iso-2022-jp')
msg3.set_payload([parts, MIMEMessage(msg4)])
fp = file(args.pop(0), 'wb')
fp.write(msg3.as_string(0))
fp.close()
return
示例12: _encodedHeader
def _encodedHeader(value, encoding):
"""
Given a value (or list of values) and an ecoding, return it
encoded as per rfc2047 for use in a MIME message header.
>>> from Products.listen.content.mailboxer_list import MailBoxerMailingList
If the input can be converted to ascii, it will be, regardless
of the encoding argument:
>>> MailBoxerMailingList._encodedHeader('blah', 'utf8')
'blah'
If it can be encoded to the target encoding, it will be, and
then encoded as per rfc2047:
>>> input = u'\xbfhmm?'
>>> MailBoxerMailingList._encodedHeader(input, 'utf8')
'=?utf8?b?wr9obW0/?='
>>> MailBoxerMailingList._encodedHeader(input.encode('utf8'), 'utf8')
'=?utf8?b?wr9obW0/?='
>>> raw = 'a string \345\276\267\345\233\275'
>>> MailBoxerMailingList._encodedHeader(raw, 'utf8')
'=?utf8?b?YSBzdHJpbmcg5b635Zu9?='
All other cases will raise an exception. Typically this means
a raw byte string in an incompatible encoding:
>>> MailBoxerMailingList._encodedHeader(input.encode('latin1'), 'utf8')
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbf in position 0: unexpected code byte
"""
try:
value = value.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
try:
value = Header(value.encode(encoding), encoding).encode()
except UnicodeDecodeError:
try:
value = Header(value, encoding).encode()
except UnicodeDecodeError:
logger.error("Could not guess encoding of raw bytestring %r, there is probably a bug in the code that created this header." % value)
raise
return value
示例13: forbid_multi_line_headers
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
encoding = encoding or "utf-8"
val = force_unicode(val, encoding)
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 = val.encode("ascii")
except UnicodeEncodeError:
if name.lower() in ("to", "from", "cc"):
result = []
for nm, addr in getaddresses((val,)):
nm = str(Header(nm.encode(encoding), encoding))
result.append(formataddr((nm, str(addr))))
val = ", ".join(result)
else:
val = Header(val.encode(encoding), encoding)
else:
if name.lower() == "subject":
val = Header(val)
return name, val
示例14: sendMailMessage
def sendMailMessage(self, xMailMessage):
COMMASPACE = ', '
if dbg:
print >> sys.stderr, "PyMailSMPTService sendMailMessage"
recipients = xMailMessage.getRecipients()
sendermail = xMailMessage.SenderAddress
sendername = xMailMessage.SenderName
subject = xMailMessage.Subject
ccrecipients = xMailMessage.getCcRecipients()
bccrecipients = xMailMessage.getBccRecipients()
if dbg:
print >> sys.stderr, "PyMailSMPTService subject", subject
print >> sys.stderr, "PyMailSMPTService from", sendername.encode('utf-8')
print >> sys.stderr, "PyMailSMTPService from", sendermail
print >> sys.stderr, "PyMailSMPTService send to", recipients
attachments = xMailMessage.getAttachments()
textmsg = Message()
content = xMailMessage.Body
flavors = content.getTransferDataFlavors()
if dbg:
print >> sys.stderr, "PyMailSMPTService flavors len", len(flavors)
#Use first flavor that's sane for an email body
for flavor in flavors:
if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find('text/plain') != -1:
if dbg:
print >> sys.stderr, "PyMailSMPTService mimetype is", flavor.MimeType
textbody = content.getTransferData(flavor)
try:
textbody = textbody.value
except:
pass
textbody = textbody.encode('utf-8')
if len(textbody):
mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
if mimeEncoding.find('charset=UTF-8') == -1:
mimeEncoding = mimeEncoding + "; charset=UTF-8"
textmsg['Content-Type'] = mimeEncoding
textmsg['MIME-Version'] = '1.0'
textmsg.set_payload(textbody)
break
if (len(attachments)):
msg = MIMEMultipart()
msg.epilogue = ''
msg.attach(textmsg)
else:
msg = textmsg
hdr = Header(sendername, 'utf-8')
hdr.append('<'+sendermail+'>','us-ascii')
msg['Subject'] = subject
msg['From'] = hdr
msg['To'] = COMMASPACE.join(recipients)
if len(ccrecipients):
msg['Cc'] = COMMASPACE.join(ccrecipients)
if xMailMessage.ReplyToAddress != '':
msg['Reply-To'] = xMailMessage.ReplyToAddress
mailerstring = "OpenOffice.org 2.0 via Caolan's mailmerge component"
try:
ctx = uno.getComponentContext()
aConfigProvider = ctx.ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider")
prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
prop.Name = "nodepath"
prop.Value = "/org.openoffice.Setup/Product"
aSettings = aConfigProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",
(prop,))
mailerstring = aSettings.getByName("ooName") + " " + \
aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component"
except:
pass
msg['X-Mailer'] = mailerstring
msg['Date'] = formatdate(localtime=True)
for attachment in attachments:
content = attachment.Data
flavors = content.getTransferDataFlavors()
flavor = flavors[0]
ctype = flavor.MimeType
maintype, subtype = ctype.split('/', 1)
msgattachment = MIMEBase(maintype, subtype)
data = content.getTransferData(flavor)
msgattachment.set_payload(data)
Encoders.encode_base64(msgattachment)
fname = attachment.ReadableName
try:
fname.encode('ascii')
except:
fname = ('utf-8','',fname.encode('utf-8'))
msgattachment.add_header('Content-Disposition', 'attachment', \
filename=fname)
msg.attach(msgattachment)
#.........这里部分代码省略.........
示例15: sendMailMessage
def sendMailMessage(self, xMailMessage):
COMMASPACE = ", "
if dbg:
print >>sys.stderr, "PyMailSMPTService sendMailMessage"
recipients = xMailMessage.getRecipients()
sendermail = xMailMessage.SenderAddress
sendername = xMailMessage.SenderName
subject = xMailMessage.Subject
ccrecipients = xMailMessage.getCcRecipients()
bccrecipients = xMailMessage.getBccRecipients()
if dbg:
print >>sys.stderr, "PyMailSMPTService subject", subject
print >>sys.stderr, "PyMailSMPTService from", sendername.encode("utf-8")
print >>sys.stderr, "PyMailSMTPService from", sendermail
print >>sys.stderr, "PyMailSMPTService send to", recipients
attachments = xMailMessage.getAttachments()
content = xMailMessage.Body
flavors = content.getTransferDataFlavors()
flavor = flavors[0]
if dbg:
print >>sys.stderr, "PyMailSMPTService mimetype is", flavor.MimeType
textbody = content.getTransferData(flavor)
textmsg = Message()
mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
textmsg["Content-Type"] = mimeEncoding
textmsg["MIME-Version"] = "1.0"
textmsg.set_payload(textbody.encode("utf-8"))
if len(attachments):
msg = MIMEMultipart()
msg.epilogue = ""
msg.attach(textmsg)
else:
msg = textmsg
hdr = Header(sendername, "utf-8")
hdr.append("<" + sendermail + ">", "us-ascii")
msg["Subject"] = subject
msg["From"] = hdr
msg["To"] = COMMASPACE.join(recipients)
if len(ccrecipients):
msg["Cc"] = COMMASPACE.join(ccrecipients)
if xMailMessage.ReplyToAddress != "":
msg["Reply-To"] = xMailMessage.ReplyToAddress
msg["X-Mailer"] = "OpenOffice.org 2.0 via Caolan's mailmerge component"
msg["Date"] = formatdate(localtime=True)
for attachment in attachments:
content = attachment.Data
flavors = content.getTransferDataFlavors()
flavor = flavors[0]
ctype = flavor.MimeType
maintype, subtype = ctype.split("/", 1)
msgattachment = MIMEBase(maintype, subtype)
data = content.getTransferData(flavor)
msgattachment.set_payload(data)
Encoders.encode_base64(msgattachment)
msgattachment.add_header("Content-Disposition", "attachment", filename=attachment.ReadableName)
msg.attach(msgattachment)
uniquer = {}
for key in recipients:
uniquer[key] = True
if len(ccrecipients):
for key in ccrecipients:
uniquer[key] = True
if len(bccrecipients):
for key in bccrecipients:
uniquer[key] = True
truerecipients = uniquer.keys()
if dbg:
print >>sys.stderr, "PyMailSMPTService recipients are", truerecipients
self.server.sendmail(sendermail, truerecipients, msg.as_string())