Airflow - how to make EmailOperator html_content dynamic?

I am looking for a method that allows you to dynamically set the contents of emails sent by the EmailOperator task. Ideally, I would like the email content to depend on the results of the xcom call, preferably with the html_content argument.

alert = EmailOperator(
    task_id=alertTaskID,
    to='please@dontreply.com',
    subject='Airflow processing report',
    html_content='raw content #2',
    dag=dag
)

I notice that Airflow docs say that xcom calls can be embedded in templates. Perhaps there is a way to formulate xcom pull using a template on the specified task id, and then pass the result as html_content? Thanks

+4
source share
3 answers

. , + xcom. dag. BashOperator EmailOperator, .

def pushparam(param, ds, **kwargs):
    kwargs['ti'].xcom_push(key='specificKey', value=param)
    return 

loadxcom = PythonOperator(
    task_id='loadxcom',
    python_callable=pushparam,
    provide_context=True,        
    op_args=['your_message_here'],
    dag=dag)

template2 = """
    echo "{{ params.my_param }}"
    echo "{{ task_instance.xcom_pull(task_ids='loadxcom', key='specificKey') }}"
"""
t5 = BashOperator(
    task_id='tt2',
    bash_command=template2,
    params={'my_param': 'PARAMETER1'},
    dag=dag)

, - :

airflow test dag_name loadxcom 2015-12-31
airflow test dag_name tt2 2015-12-31

EmailOperator - , ...

+6

, jinja EmailOperator,

from airflow.operators.email_operator import EmailOperator
from datetime import timedelta, datetime

email_task = EmailOperator(
    to='some@email.com',
    task_id='email_task',
    subject='Templated Subject: start_date {{ ds }}',
    params={'content1': 'random'},
    html_content="Templated Content: content1 - {{ params.content1 }}  task_key - {{ task_instance_key_str }} test_mode - {{ test_mode }} task_owner - {{ task.owner}} hostname - {{ ti.hostname }}",
    dag=dag)

,

airflow test dag_name email_task 2017-05-10
+3

PythonOperator + send_email :

from airflow.operators import PythonOperator
from airflow.utils.email import send_email


def email_callback(**kwargs):
    with open('/path/to.html') as f:
        content = f.read()
    send_email(
        to=[
            # emails
        ],
        subject='subject',
        html_content=content,
    )


email_task = PythonOperator(
    task_id='task_id',
    python_callable=email_callback,
    provide_context=True,
    dag=dag,
)
0

Source: https://habr.com/ru/post/1624837/


All Articles