本文整理汇总了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