IMAP email sensor with multiple attributes?

Im new to HA & trying to setup a imap content sensor which should be able to read multiple attributes from email body. So far i have sucessfully intrigated my gmail and sensor is working fine.

template:
  - trigger:
      - platform: event
        event_type: "imap_content"
        id: "GPSposition"
        event_data:
          subject: pos
    sensor:
      - name: gayangps
        state: "{{ trigger.event.data['date'] }}"
        attributes:
          latitude: "WHAT SHOULD BE HERE"
          longitude: "WHAT SHOULD BE HERE"

My requirement is to use this sensor as a tracker to show position in a map. Position is received by an email with subject of ¨pos¨.

How to get these two attributes,Latitude and Longitude to be identified from email body? I can customize email body in anyway since its manually sent.

Or is there anyother method to achieve my goal?

If you have control over the message and you won’t be including anything else in the message body, one option is to format it as json like: {"latitude": 123, "longitude": 654}.

Then you can extract those values in you attributes using the from_json() filter:

IMAP Content sensor
template:
  - trigger:
      - platform: event
        event_type: "imap_content"
        id: "GPSposition"
        event_data:
          subject: pos
    sensor:
      - name: gayangps
        state: "{{ trigger.event.data['date'] }}"
        attributes:
          latitude: "{{ (trigger.event.data['text']|from_json)['latitude'] }}"
          longitude: "{{ (trigger.event.data['text']|from_json)['longitude'] }}"

However, if the end goal is to create a device tracker, and you don’t actually need the intermediary sensor, you might be better off using the event trigger in an automation with a service call to device_tracker.see. Just make sure you make the trigger event data as specific as possible.

alias: Assign GPS Coords from Email content 
trigger:
  - platform: event
    event_type: "imap_content"
    id: "GPSposition"
    event_data:
      subject: pos
condition:
  - condition: template
    value_template: "{{ trigger.event.data['initial'] }}"
action:
  - variable:
      text_json: "{{ trigger.event.data['text']|from_json }}"
  - service: device_tracker.see
    data:
      dev_id: example
      gps: "{{ [text_json.latitude, text_json.longitude] }}"

Thanks for reply. I did as you said but then got this error in log

> ERROR (MainThread) [homeassistant.config] Invalid config for 'template' at configuration.yaml, line 25: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value 'sensor->0->attributes->latitude', got "{{ trigger.event.data['text']|from_json)['latitude'] }}"

There is a missing ( between {{ and trigger.

"{{ (trigger....
1 Like