Documentation on how to retrieve the from, to, subject and body #333
Replies: 1 comment
-
|
Accessing the value of a header for an email object in python is relatively easy provided you know the key, but accessing the body is more difficult. Keys for email headers are case-agnostic (e.g., "to", "To", and "TO" are equally acceptable). It may, therefore, be necessary to determine the key before you can retrieve the value. The example provided below does not account for this possibility nor for many other cases. To retrieve the body it is important to note that def test_email_headers_and_body(self, smtpd: AuthController) -> NoReturn:
'''
Get email headers and body once received.
'''
def _get_body(
message: Union[Message, EmailMessage]
) -> Union[bytes, None, str]:
'''
Helper method to extract the body from an email message.
Code not tested in production.
'''
if message.is_multipart():
# handle a multipart message
for part in message.walk():
dispo = part.get_content_disposition()
if (part.get_content_type() == "text/plain" and
dispo != "attachment"):
return part.get_payload(decode=True)
return message.get_payload(decode=True)
# Generate an email.message.EmailMessage to send
sender = "from@example.org"
to = ["recipient1@example.org", "recipient2@example.org"]
subject = "This is an email"
content = "This is plain text email body"
msg = EmailMessage()
msg["Sender"] = sender
msg["Reply-To"] = sender
msg["To"] = ", ".join(to)
msg["Subject"] = subject
msg.set_content(content)
# Send the message using smtplib.SMTP
with SMTP(smtpd.hostname, smtpd.port) as client:
client.send_message(msg)
# Ensure we have received only one message!
assert len(smtpd.messages) == 1
# Test that the message is as expected.
for rcvd in smtpd.messages:
assert rcvd["Sender"] == msg["Sender"]
assert rcvd["Reply-To"] == sender
body = _get_body(rcvd)
if isinstance(body, bytes):
body = body.decode()
assert content in bodyA more complete answer to the question, for anyone stumbling across this discussion in the future, must include that it may make more sense to write tests against the While I am delighted when I see SMTPFix being used, it is intended to help fill a need for cases that require a SMTP server for testing. There may be, and in my opinion often are, better ways to test email related code. Note: While out of scope for this discussion it may be useful to note that |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
The test code in README documentation asserts for messages count but i would like to know how to get the from, to, subject and body from the email that was sent
Can you help?
Beta Was this translation helpful? Give feedback.
All reactions