I'm getting an attachment from an email Message object and creating a tempfile like so:
import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write(payload.get_payload(decode=True))
Is it possible to get the md5 out of this tempfile or do I have to save it to disk and then get the md5? Something like so would be what I'm aiming for:
import hashlib
print(hashlib.md5(temp).hexdigest())
But I run into this error
TypeError: object supporting the buffer API required
Source Code to Find HashHash functions are available in the hashlib module. We loop till the end of the file using a while loop. On reaching the end, we get empty bytes object. In each iteration, we only read 1024 bytes (this value can be changed according to our wish) from the file and update the hashing function.
Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.
When you call the hashlib.md5 command it does expect a string like object instead of a file handle. But guess what you already have that. So there is no need to read it back from the file.
import tempfile
import hashlib
with tempfile.NamedTemporaryFile() as temp:
data = payload.get_payload(decode=True)
temp.write(data)
print(hashlib.md5(data).hexdigest())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With