Look for a specific word in the body of the email, then trigger an action

hi

i have some code to trigger an action
i receive an email from my alarm system, based on a keyword in the body of that mail i want to turn on a switch
the code is working fine
IF only the correct word in in the body , like ON or OFF
but the email i get from my alarm has lots of text in it, so i want to LOOK for a keyword in that body

what do i need to change in my code:

configuration :

  - platform: imap_email_content
    server: imap.gmail.com
    port: 993
    name: alarmmail
    username: !secret gmail_username
    password: !secret gmail_password
    scan_interval: 10
    senders:
      - [email protected]
    value_template: "{{ body }}"

automation :

- action:
  - service: switch.turn_on
    entity_id: switch.home_mode
  alias: Home mode aan
  condition: []
  id: '1513037592904'
  trigger:
  - entity_id: sensor.alarmmail
    platform: state
    to: 'ON'
    
- action:
  - service: switch.turn_off
    entity_id: switch.home_mode
  alias: Home mode uit
  condition: []
  id: '1513037592905'
  trigger:
  - entity_id: sensor.alarmmail
    platform: state
    to: 'OFF'

Remove value_template: "{{ body }}" from your imap_email_content sensor config. Emails are often larger than the 255 character limit, and removing it makes the body into an attribute, which doesn’t that limit. You can then use automations like this:

- alias: Home mode aan
  id: '1513037592904'
  trigger:
  - entity_id: sensor.alarmmail
    platform: state
  condition:
  - condition: template
    value_template: '{{ "YOUR-ARM-KEYWORD" in states.sensor.alarmmail.attributes.body }}'
  action:
  - service: switch.turn_on
    entity_id: switch.home_mode
- alias: Home mode uit
  id: '1513037592905'
  trigger:
  - entity_id: sensor.alarmmail
    platform: state
  condition:
  - condition: template
    value_template: '{{ "YOUR-DISARM-WORD" in states.sensor.alarmmail.attributes.body }}'
  action:
  - service: switch.turn_off
    entity_id: switch.home_mode

cool, almost there ! ineed , i also had the 255 limit
the only problem i have now, is that seems my alarm mail has some kind of coded message like :

body
QWFuDQoNCu+7vw0KW2NpZDppbWFnZTAwMS5naWZAMDFENDJEQTQuRkQ2NUEzMTBdDQoNCg0KRGVh
ciBGYWJpbyBQZXJnb2xhDQoNCkV2ZW50IFVuc2V0IC0gJ1BlcmdvbGEgUXVpbnRlbnMnLCAnRkFC
SU8gUEVSR09MQSc …

how can i decode that first ? or make it readable?

That’s beyond what the imap_email_content platform can handle. The thread, Decode email body from imap email content sensor, provides an alternative. Personally, I’ve moved to Node-RED to do my email parsing.

Ok, gonna have a look, thnx again for the information!!

ok, it was quite easy, just change 1 line of code in sensor file from home assistant :slight_smile:

see here, my reply to that thread, for others maybe …