diff --git a/frappe/email/receive.py b/frappe/email/receive.py index 85cf24ec5c..55c1efb22b 100644 --- a/frappe/email/receive.py +++ b/frappe/email/receive.py @@ -10,6 +10,7 @@ from frappe.utils import extract_email_id, convert_utc_to_user_timezone, now, ci from frappe.utils.scheduler import log from email_reply_parser import EmailReplyParser from email.header import decode_header +from frappe.utils.file_manager import get_random_filename class EmailSizeExceededError(frappe.ValidationError): pass class EmailTimeoutError(frappe.ValidationError): pass @@ -236,11 +237,24 @@ class Email: return part.get_payload() def get_attachment(self, part, charset): - self.attachments.append({ - 'content_type': part.get_content_type(), - 'fname': cstr(decode_header(part.get_filename())[0][0]), - 'fcontent': part.get_payload(decode=True), - }) + fcontent = part.get_payload(decode=True) + + if fcontent: + content_type = part.get_content_type() + fname = part.get_filename() + if fname: + try: + fname = cstr(decode_header(fname)[0][0]) + except: + fname = get_random_filename(content_type=content_type) + else: + fname = get_random_filename(content_type=content_type) + + self.attachments.append({ + 'content_type': content_type, + 'fname': fname, + 'fcontent': fcontent, + }) def save_attachments_in_doc(self, doc): """Save email attachments in given document.""" diff --git a/frappe/utils/file_manager.py b/frappe/utils/file_manager.py index 043347d9c3..6c91a10d17 100644 --- a/frappe/utils/file_manager.py +++ b/frappe/utils/file_manager.py @@ -96,8 +96,7 @@ def extract_images_from_html(doc, fieldname): filename = headers.split("filename=")[-1] else: mtype = headers.split(";")[0] - extn = mimetypes.guess_extension(mtype) - filename = random_string(7) + extn + filename = get_random_filename(content_type=mtype) # TODO fix this file_url = save_file(filename, content, doc.doctype, doc.name, decode=True).get("file_url") @@ -111,6 +110,16 @@ def extract_images_from_html(doc, fieldname): if frappe.flags.has_dataurl: doc.set(fieldname, content) +def get_random_filename(extn=None, content_type=None): + if extn: + if not extn.startswith("."): + extn = "." + extn + + elif content_type: + extn = mimetypes.guess_extension(content_type) + + return random_string(7) + (extn or "") + def save_file(fname, content, dt, dn, decode=False): if decode: if isinstance(content, unicode):