本文整理匯總了Python中email.message.EmailMessage.add_header方法的典型用法代碼示例。如果您正苦於以下問題:Python EmailMessage.add_header方法的具體用法?Python EmailMessage.add_header怎麽用?Python EmailMessage.add_header使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類email.message.EmailMessage
的用法示例。
在下文中一共展示了EmailMessage.add_header方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: MHTML
# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_header [as 別名]
class MHTML(object):
def __init__(self):
self._msg = EmailMessage()
self._msg['MIME-Version'] = '1.0'
self._msg.add_header('Content-Type', 'multipart/related', type='text/html')
def add(self, location: str, content_type: str, payload: str, encoding: str = 'quoted-printable') -> None:
resource = EmailMessage()
if content_type == 'text/html':
resource.add_header('Content-Type', 'text/html', charset='utf-8')
else:
resource['Content-Type'] = content_type
if encoding == 'quoted-printable':
resource['Content-Transfer-Encoding'] = encoding
resource.set_payload(quopri.encodestring(payload.encode()))
elif encoding == 'base64':
resource['Content-Transfer-Encoding'] = encoding
resource.set_payload(base64.b64encode(payload))
elif encoding == 'base64-encoded': # Already base64 encoded
resource['Content-Transfer-Encoding'] = 'base64'
resource.set_payload(payload)
else:
raise ValueError('invalid encoding')
resource['Content-Location'] = location
self._msg.attach(resource)
def __str__(self) -> str:
return str(self._msg)
def __bytes__(self) -> bytes:
return bytes(self._msg)
示例2: create_mail
# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_header [as 別名]
def create_mail(sender, recipient, subject, body, attachments, gpgme_ctx):
"""Create an email either as single or multi-part with attachments.
"""
msg = EmailMessage(policy=mailgen_policy)
msg.set_content(body)
attachment_parent = msg
if gpgme_ctx is not None:
msg.make_mixed()
attachment_parent = next(msg.iter_parts())
if attachments:
for args, kw in attachments:
attachment_parent.add_attachment(*args, **kw)
if gpgme_ctx is not None:
signed_bytes = attachment_parent.as_bytes()
hash_algo, signature = detached_signature(gpgme_ctx, signed_bytes)
msg.add_attachment(signature, "application", "pgp-signature",
cte="8bit")
# the signature part should now be the last of two parts in the
# message, the first one being the signed part.
signature_part = list(msg.iter_parts())[1]
if "Content-Disposition" in signature_part:
del signature_part["Content-Disposition"]
msg.replace_header("Content-Type", "multipart/signed")
micalg = hash_algorithms.get(hash_algo)
if micalg is None:
raise RuntimeError("Unexpected hash algorithm %r from gpgme"
% (signature[0].hash_algo,))
msg.set_param("protocol", "application/pgp-signature")
msg.set_param("micalg", micalg)
msg.add_header("From", sender)
msg.add_header("To", recipient)
msg.add_header("Subject", subject)
msg.add_header("Date", formatdate(timeval=None, localtime=True))
# take the domain part of sender as the domain part of the message
# ID. We assume that sender has the form [email protected], so we can
# just the part of sender after the '@'.
sender_domain = sender.partition("@")[-1]
if not sender_domain:
raise RuntimeError("Could not extract the domain from the sender (%r)"
" for the Message-ID" % (sender,))
msg.add_header("Message-Id", make_msgid(domain=sender_domain))
return msg
示例3: add
# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_header [as 別名]
def add(self, location: str, content_type: str, payload: str, encoding: str = 'quoted-printable') -> None:
resource = EmailMessage()
if content_type == 'text/html':
resource.add_header('Content-Type', 'text/html', charset='utf-8')
else:
resource['Content-Type'] = content_type
if encoding == 'quoted-printable':
resource['Content-Transfer-Encoding'] = encoding
resource.set_payload(quopri.encodestring(payload.encode()))
elif encoding == 'base64':
resource['Content-Transfer-Encoding'] = encoding
resource.set_payload(base64.b64encode(payload))
elif encoding == 'base64-encoded': # Already base64 encoded
resource['Content-Transfer-Encoding'] = 'base64'
resource.set_payload(payload)
else:
raise ValueError('invalid encoding')
resource['Content-Location'] = location
self._msg.attach(resource)
示例4: encrypt
# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_header [as 別名]
def encrypt(message, certs, algorithm='aes256_cbc'):
"""
Takes the contents of the message parameter, formatted as in RFC 2822 (type str or message), and encrypts them,
so that they can only be read by the intended recipient specified by pubkey.
:return: the new encrypted message (type str or message, as per input).
"""
# Get the chosen block cipher
block_cipher = get_cipher(algorithm)
if block_cipher == None:
raise ValueError('Unknown block algorithm')
# Get the message content. This could be a string, or a message object
passed_as_str = isinstance(message, str)
if passed_as_str:
msg = message_from_string(message)
else:
msg = message
# Extract the message payload without conversion, & the outermost MIME header / Content headers. This allows
# the MIME content to be rendered for any outermost MIME type incl. multipart
pl = EmailMessage()
for i in msg.items():
hname = i[0].lower()
if hname == 'mime-version' or hname.startswith('content-'):
pl.add_header(i[0], i[1])
pl._payload = msg._payload
content = pl.as_string()
recipient_infos = []
for recipient_info in __iterate_recipient_infos(certs, block_cipher.session_key):
if recipient_info == None:
raise ValueError('Unknown public-key algorithm')
recipient_infos.append(recipient_info)
# Encode the content
encrypted_content_info = block_cipher.encrypt(content)
# Build the enveloped data and encode in base64
enveloped_data = cms.ContentInfo({
'content_type': 'enveloped_data',
'content': {
'version': 'v0',
'recipient_infos': recipient_infos,
'encrypted_content_info': encrypted_content_info
}
})
encoded_content = '\n'.join(wrap_lines(b64encode(enveloped_data.dump()), 64))
# Create the resulting message
result_msg = MIMEText(encoded_content)
overrides = (
('MIME-Version', '1.0'),
('Content-Type', 'application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m'),
('Content-Transfer-Encoding', 'base64'),
('Content-Disposition', 'attachment; filename=smime.p7m')
)
for name, value in list(msg.items()):
if name in [x for x, _ in overrides]:
continue
result_msg.add_header(name, value)
for name, value in overrides:
if name in result_msg:
del result_msg[name]
result_msg[name] = value
# return the same type as was passed in
if passed_as_str:
return result_msg.as_string()
else:
return result_msg