Hold the display of the last state until it changes, instead of unknown | IMAP template

Hello, with the imap template, I am parsing the (number) status of the bank account from the body of the email


  - platform: imap_email_content
    server: mail.server.com
    port: 993
    username: [email protected]
    password: coolpassword
    folder: Inbox
    senders:
      - [email protected]

  - platform: template
    sensors:
      fiodobe_recent_status:
        friendly_name: Bank Notification
        unit_of_measurement: Currency
        value_template: >-
          {{ state_attr('sensor.mail_server_com','body') | regex_findall_index(find='(\d+\s\,?\d+)', index=0, ignorecase=False) }}

Amounts don’t come every day, and it happens that after a few days, Lovelace card si displayed unknown instead of the (last) actual number. Is it possible to “add something to the code” that will keep the last state until the number changes? Thank you.

Try this

        value_template: >
          {% set fiodobe = state_attr('sensor.mail_server_com','body') | regex_findall_index(find='(\d+\s\,?\d+)', index=0, ignorecase=False) %}
          {% if fiodobe not in ['unknown', 'unavailable', 'none'] %}
            {{ fiodobe }}
          {% else %}
            {{ states('sensor.fiodobe_recent_status') }}
          {% endif %}
1 Like

I will manually change the record in MySQL or I will wait for a new email, so that I can confirm the functionality of the provided code modification. I’ll let you know, thank you.

Hi. It works, but after saving (a new template from your code) and restarting, the new template “takes” the first (oldest) e-mail from today (there are three emails today in total) and not the last (current). Is that okay, and after days without an incoming email, the last state value will remain until next week, for example? Thank you.

After second restart (core upgrade) it show unavailable …

↑ This is working solution ↑