Write JSON structure for IMAP mails

Hey there, I want to read mails with the IMAP integration of Home Assistant. This works very well. But I want to save the last 10 mails that were received and according to my conditions. I tried several options like MQTT but it’s problematic when you want to use an JSON array then and also use the data again. I need to be able to read it again after being saved.

I really don’t know how to do it. I tried it with notify.file but got several problems that nothing would be saved. The last try for my automation now looked like this:

alias: Save mails
description: >-
  Saves the last 10 mails as JSON-Array and updates variables.
triggers:
  - event_type: imap_content
    id: custom_event
    trigger: event
actions:
  - variables:
      new_email: |
        {{
          {
            "subject": trigger.event.data.subject,
            "sender": trigger.event.data.sender,
            "message": trigger.event.data.text,
            "folder": trigger.event.data.folder,
            "server": trigger.event.data.server,
            "username": trigger.event.data.username,
            "search": trigger.event.data.search
          }
        }}
  - variables:
      current_emails: >
        {% set history = states('sensor.email_history') %} {{ (history if
        history not in ['unknown', 'unavailable', 'None'] else '[]') | from_json
        }}
  - variables:
      updated_emails: >
        {{ (current_emails + [new_email])[-10:] }}  
  - data:
      topic: email/history
      payload: "{{ {'emails': updated_emails} | tojson }}"
      retain: true
    action: mqtt.publish

But this won’t work. In the end, I really want to be able to see a list in a dashboard with the latest 10 subjects of mails. But I don’t know how to do this. Having 10 separate sensors for this might be possible somehow but sounds ridiculous to me.