Get Mimetype for valid Image on Receiving Email via Google App Engine
How can I get the mimetype from an attachment when I receive a email via Google App Engine?
class ReceiveEmail开发者_开发技巧(InboundMailHandler):
def receive(self,message):
sender = parseaddr(message.sender)[1]
receiver = parseaddr(message.to)[1]
# Attachments
try:
if message.attachments :
# Attachments Image
for a in message.attachments:
t = a[0].split('.')
t = t[len(t)-1].lower()
if t == 'png' or t == 'jpg' or t == 'jpeg' or t == 'gif':
logging.info('Image is correct')
else:
logging.info('Image is wrong')
except:
# nothing
I have to know if the attached file in email is really an image? If I don't check this the user can upload an text.xml file which is only renamed to text.jpg.
How can I solve this problem?
I'm sorry, but I'm not sure if I have fully undestood the question.
You can use the built-in module mimetypes to identify the Mimetype. But the functions on this module will search for mimetypes on the file name only, so the user will be able to upload a text.xml renamed to text.jpg and be interpreted as a image.
If you are working with images only, maybe you can try to open the file as a PIL object to identify if it is a valid file, and work with the exception if it fails.
message
is an instance of InboundEmailMessage, which has a method 'bodies'. bodies returns a list of (content_type, payload) tuples, so you can iterate over all the bodies like this:
for content_type, payload in message.bodies():
# Do something with each part of the message
Alternately, you can pass a mimetype to message.bodies
, which will return only parts with that mimetype.
You can also determine the mimetype from the filename, or using the mimetypes
module as Nemeth suggests.
精彩评论