'If no parent found, create a new reference document'

def create_new_parent(self, communication, email):

    parent = frappe.new_doc(self.append_to)
    if self.subject_field:
        parent.set(self.subject_field, frappe.as_unicode(email.subject)[:140])
    if self.sender_field:
        parent.set(self.sender_field, frappe.as_unicode(email.from_email))
    parent.flags.ignore_mandatory = True
    try:
        parent.insert(ignore_permissions=True)
    except frappe.DuplicateEntryError:
        parent_name = frappe.db.get_value(self.append_to, {self.sender_field: email.from_email})
        if parent_name:
            parent.name = parent_name
        else:
            parent = None
    communication.is_first = True
    return parent
