Skip to content

airflow.exceptions.AirflowException: The smtp connection should be loaded before! #49920

Description

@dramis

Apache Airflow Provider(s)

smtp

Versions of Apache Airflow Providers

apache-airflow-providers-smtp 2.0.3

Apache Airflow version

3.0.0

Operating System

debian 12

Deployment

Virtualenv installation

Deployment details

New airflow install on a new server

What happened

Got a error message sending email on dag succes:
airflow.exceptions.AirflowException: The smtp connection should be loaded

I correct this problem with a custom notifier bases on airflow.providers.smtp.notifications.smtp import SmtpNotifier,:

def notify(self, context):

     with SmtpHook(smtp_conn_id=self.smtp_conn_id) as smtp_hook:

         """Send a email via smtp server."""
         fields_to_re_render = []
         if self.from_email is None:
             if smtp_hook.from_email is not None:
                 self.from_email = smtp_hook.from_email
             else:
                 raise ValueError("You should provide `from_email` or define it in the connection")
             fields_to_re_render.append("from_email")
         if self.subject is None:
             smtp_default_templated_subject_path: str
             if smtp_hook.subject_template:
                 smtp_default_templated_subject_path = smtp_hook.subject_template
             else:
                 smtp_default_templated_subject_path = (
                     Path(__file__).parent / "templates" / "email_subject.jinja2"
                 ).as_posix()
             self.subject = self._read_template(smtp_default_templated_subject_path)
             fields_to_re_render.append("subject")
         if self.html_content is None:
             smtp_default_templated_html_content_path: str
             if smtp_hook.html_content_template:
                 smtp_default_templated_html_content_path = smtp_hook.html_content_template
             else:
                 smtp_default_templated_html_content_path = (
                     Path(__file__).parent / "templates" / "email.html"
                 ).as_posix()
             self.html_content = self._read_template(smtp_default_templated_html_content_path)
             fields_to_re_render.append("html_content")
         if fields_to_re_render:
             jinja_env = self.get_template_env(dag=context["dag"])
             self._do_render_template_fields(self, fields_to_re_render, context, jinja_env, set())

         smtp_hook.send_email_smtp(
             smtp_conn_id=self.smtp_conn_id,
             from_email=self.from_email,
             to=self.to,
             subject=self.subject,
             html_content=self.html_content,
             files=self.files,
             cc=self.cc,
             bcc=self.bcc,
             mime_subtype=self.mime_subtype,
             mime_charset=self.mime_charset,
             custom_headers=self.custom_headers,
         )


after that i got this error:

UndefinedError: 'airflow.sdk.execution_time.task_runner.RuntimeTaskInstance object' has no attribute 'state'
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/sdk/bases/notifier.py", line 105 in __call__
File "/opt/airflow/venv/lib/python3.11/site-packages/smtp_thehub_provider/notifications/smtp.py", line 142 in notify
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/sdk/definitions/_internal/templater.py", line 121 in _do_render_template_fields
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/sdk/definitions/_internal/templater.py", line 177 in render_template
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/sdk/bases/notifier.py", line 57 in _render
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/sdk/definitions/_internal/templater.py", line 133 in _render
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/utils/helpers.py", line 244 in render_template_to_string
File "/opt/airflow/venv/lib/python3.11/site-packages/airflow/utils/helpers.py", line 239 in render_template
File "<template>", line 29 in root
File "/opt/airflow/venv/lib/python3.11/site-packages/jinja2/runtime.py", line 859 in _fail_with_undefined_error

What you think should happen instead

No error message and the email is sent

How to reproduce

Run this dag after configure smtp_default connection:

from airflow import DAG
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.providers.smtp.notifications.smtp import SmtpNotifier
from datetime import datetime

default_args = {
    "owner": "airflow",
}

with DAG(
    dag_id="airflow_email_test",
    start_date=datetime(2024, 1, 1),
    schedule="@daily",
    catchup=False,
    default_args=default_args,
    tags=["maintenance", "cleanup"],
) as dag:

    clean_logs = EmptyOperator(
        task_id="empty_operator",
        on_success_callback=SmtpNotifier(from_email='[email protected], to="[email protected]"),
    )

Anything else

No response

Are you willing to submit PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:bug
    needs-triage
    on Apr 28, 2025
  2. boring-cyborg commented on Apr 28, 2025

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

  3. ForeverWintr commented on Jun 11, 2025

    @ForeverWintr
    Contributor

    I see this issue in Airflow 2.11 with smtp provider 2.1.0 also.

  4. AndrewPetersonSnr commented on Jun 12, 2025

    @AndrewPetersonSnr

    Same problem with Airflow 3.0.2 version and apache-airflow-providers-smtp 2.1.0 version. Tried set connection using AIRFLOW_CONN_* env variable and after through web UI.

  5. potiuk commented on Jun 21, 2025

    @potiuk
    Member

    can you show the longs and explain in details what you've done for 3.0.2 @IIPOCTAK ?

  6. mobsean commented on Jun 26, 2025

    @mobsean

    I got the same error message with this example using task flow api:

    running Airflow 3.0.2 inside docker with docker-compose.yaml

    import pendulum
    from airflow.decorators import dag, task
    from airflow.providers.smtp.notifications.smtp import SmtpNotifier
    
    
    @dag(
        schedule='*/1 * * * *',
        start_date=pendulum.datetime(2024, 1, 8, tz='Europe/Berlin'),
        catchup=False,
        tags=["example"],
        default_args={
            "on_failure_callback": SmtpNotifier(to="[email protected]"),
            "on_retry_callback": SmtpNotifier(to="[email protected]"),
        },
    )
    def my_taskflow_dag():
        @task()
        def start():
            print("Start DAG")
    
        @task()
        def fail_task():
            raise ValueError("This Task should fail!")
    
        start() >> fail_task()
    
    
    my_taskflow_dag = my_taskflow_dag()

    I created a connection to my SMTP server in the Airflow UI (Admin → Connections).

    And on the fail_task I recieve these logs:

    [2025-06-26, 09:55:50] INFO - DAG bundles loaded: dags-folder: source="airflow.dag_processing.bundles.manager.DagBundlesManager"
    [2025-06-26, 09:55:50] INFO - Filling up the DagBag from /opt/airflow/dags/abc_test.py: source="airflow.models.dagbag.DagBag"
    [2025-06-26, 09:55:50] ERROR - Task failed with exception: source="task"
    ValueError: This Task should fail!
    File "/home/airflow/.local/lib/python[3](http://***/dags/my_taskflow_dag/runs/manual__2025-06-26T09:55:46.212450+00:00/tasks/fail_task?try_number=1#3).12/site-packages/airflow/sdk/execution_time/task_runner.py", line 867 in run
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/execution_time/task_runner.py", line 1159 in _execute_task
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/bases/operator.py", line 397 in wrapper
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/bases/decorator.py", line 251 in execute
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/bases/operator.py", line 397 in wrapper
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/standard/operators/python.py", line 216 in execute
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/standard/operators/python.py", line 239 in execute_callable
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/execution_time/callback_runner.py", line 81 in run
    
    File "/opt/airflow/dags/abc_test.py", line [4](http://***/dags/my_taskflow_dag/runs/manual__2025-06-26T09:55:46.212450+00:00/tasks/fail_task?try_number=1#4)0 in fail_task
    
    [2025-06-26, 09:55:50] ERROR - Failed to send notification: The smtp connection should be loaded before!: source="airflow.providers.smtp.notifications.smtp.SmtpNotifier"
    AirflowException: The smtp connection should be loaded before!
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/sdk/bases/notifier.py", line 105 in __call__
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 111 in notify
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 365 in from_email
    
    File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 356 in conn```
    
  7. m-rossi commented on Jul 16, 2025

    @m-rossi
    Contributor

    Had the same issue also on 3.0.3 and just submitted a fix in #53418, however in my local tests I am next stuck in #53135.

  8. TopCoder2K commented on Feb 11, 2026

    @TopCoder2K
    Contributor

    I'm also experiencing the same problem with Airflow=2.11.0 and apache-airflow-providers-smtp=2.1.0. Does this mean that the official docker image is incorrect and I should upgrade apache-airflow-providers-smtp (I cannot upgrade Airflow)?

  9. TopCoder2K commented on Feb 11, 2026

    @TopCoder2K
    Contributor

    Upgrading to apache-airflow-providers-smtp=2.4.2 (latest) doesn't help. How to use SmtpNotifier (send_smtp_notification) 🤔?

  10. shahar1 commented on Feb 11, 2026

    @shahar1
    Contributor

    Upgrading to apache-airflow-providers-smtp=2.4.2 (latest) doesn't help. How to use SmtpNotifier (send_smtp_notification) 🤔?

    Could you please describe in detail what issue you encounter after upgrading? (including code sample of a Dag, logs, anything that could help debugging this issue)

  11. TopCoder2K commented on Feb 12, 2026

    @TopCoder2K
    Contributor

    @shahar1, oh, yes, I should have done it before you answered. Here is the simplest Dag built using the docs (this and this) (the real emails are replaced):

    from airflow.decorators import dag, task
    from airflow.providers.smtp.notifications.smtp import SmtpNotifier
    
    
    @dag(
        schedule=None,
        default_args={
            "on_failure_callback": [
                SmtpNotifier(
                    to="to_email",
                    from_email="from_email",
                    subject="[Error] The task {{ ti.task_id }} failed",
                    html_content="Link to the logs: {{ ti.log_url }}",
                )
            ]
        },
    )
    def test_smtp_notification():
        @task
        def failing_task():
            raise RuntimeError("Error!")
    
        failing_task()
    
    
    test_smtp_notification()

    Here are the logs:

    2026-02-12, 07:59:28 UTC] {taskinstance.py:3336} ERROR - Task failed with exception
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 776, in _execute_task
        result = _execute_callable(context=context, **execute_callable_kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 742, in _execute_callable
        return ExecutionCallableRunner(
               ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/decorators/base.py", line 266, in execute
        return_value = super().execute(context)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 238, in execute
        return_value = self.execute_callable()
                       ^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 256, in execute_callable
        return runner.run(*self.op_args, **self.op_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/airflow/dags/test_smtp_notification.py", line 21, in failing_task
        raise RuntimeError("Error!")
    RuntimeError: Error!
    [2026-02-12, 07:59:28 UTC] {taskinstance.py:1242} INFO - Marking task as FAILED. dag_id=test_smtp_notification, task_id=failing_task, run_id=manual__2026-02-12T07:59:27.575809+00:00, execution_date=20260212T075927, start_date=20260212T075928, end_date=20260212T075928
    [2026-02-12, 07:59:28 UTC] {taskinstance.py:1580} INFO - Executing callback at index 0: SmtpNotifier
    [2026-02-12, 07:59:28 UTC] {base.py:84} INFO - Retrieving connection 'smtp_default'
    [2026-02-12, 07:59:28 UTC] {basenotifier.py:109} ERROR - Failed to send notification: 'NoneType' object has no attribute 'close'
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 282, in _run_raw_task
        TaskInstance._execute_task_with_callbacks(
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 3184, in _execute_task_with_callbacks
        result = self._execute_task(context, task_orig)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 3208, in _execute_task
        return _execute_task(self, context, task_orig)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 776, in _execute_task
        result = _execute_callable(context=context, **execute_callable_kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 742, in _execute_callable
        return ExecutionCallableRunner(
               ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/decorators/base.py", line 266, in execute
        return_value = super().execute(context)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 238, in execute
        return_value = self.execute_callable()
                       ^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 256, in execute_callable
        return runner.run(*self.op_args, **self.op_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/airflow/dags/test_smtp_notification.py", line 21, in failing_task
        raise RuntimeError("Error!")
    RuntimeError: Error!
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 140, in notify
        smtp.send_email_smtp(
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 214, in send_email_smtp
        raise AirflowException("The 'smtp_client' should be initialized before!")
    airflow.exceptions.AirflowException: The 'smtp_client' should be initialized before!
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/notifications/basenotifier.py", line 107, in __call__
        self.notify(context)
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 139, in notify
        with self.hook as smtp:
             ^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 72, in __exit__
        self.smtp_client.close()
        ^^^^^^^^^^^^^^^^^^^^^^
    AttributeError: 'NoneType' object has no attribute 'close'

    I'm basing on the default Compose file with Airflow=2.11.0. If I remove the from_email (which is already given in the Web UI Connection tab), I get the error stated in the issue head:

    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/notifications/basenotifier.py", line 107, in __call__
        self.notify(context)
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 111, in notify
        if self.hook.from_email is not None:
           ^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 365, in from_email
        return self.conn.extra_dejson.get("from_email")
               ^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 356, in conn
        raise AirflowException("The smtp connection should be loaded before!")
    airflow.exceptions.AirflowException: The smtp connection should be loaded before!

    What I have already done:

    • double checked the connection in the Web UI, checked that smtp-server (a Docker container with Mailpit) is reachable from within the worker and scheduler containers:
      (airflow)nc -zv smtp-server 1025
      Connection to smtp-server (172.18.0.3) 1025 port [tcp/*] succeeded!
    • checked that the connection is correctly retrieved by Airflow:
      from airflow.hooks.base import BaseHook
      
      conn = BaseHook.get_connection("smtp_default")
      print(conn.host, conn.port, conn.extra)  # Prints smtp-server 1025 {"from_email": "from_email", "timeout": 30, "retry_limit": 0, "disable_tls": true, "disable_ssl": true}
    • tried SmtpHook directly and with but again got airflow.exceptions.AirflowException: The 'smtp_client' should be initialized before!:
      def failure_callback(context):
          with SmtpHook(smtp_conn_id="smtp_default") as hook:
              hook.send_email_smtp(
                  to="to_email",
                  from_email="from_email",
                  subject="Test failure",
                  html_content="Body",
              )
      
      @dag(
          schedule=None,
          default_args={
              "on_failure_callback": [
                  failure_callback
              ]
          },
      )
      ...
  12. shahar1 commented on Feb 12, 2026

    @shahar1
    Contributor

    @shahar1, oh, yes, I should have done it before you answered. Here is the simplest Dag built using the docs (this and this) (the real emails are replaced):

    from airflow.decorators import dag, task
    from airflow.providers.smtp.notifications.smtp import SmtpNotifier
    
    
    @dag(
        schedule=None,
        default_args={
            "on_failure_callback": [
                SmtpNotifier(
                    to="to_email",
                    from_email="from_email",
                    subject="[Error] The task {{ ti.task_id }} failed",
                    html_content="Link to the logs: {{ ti.log_url }}",
                )
            ]
        },
    )
    def test_smtp_notification():
        @task
        def failing_task():
            raise RuntimeError("Error!")
    
        failing_task()
    
    
    test_smtp_notification()

    Here are the logs:

    2026-02-12, 07:59:28 UTC] {taskinstance.py:3336} ERROR - Task failed with exception
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 776, in _execute_task
        result = _execute_callable(context=context, **execute_callable_kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 742, in _execute_callable
        return ExecutionCallableRunner(
               ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/decorators/base.py", line 266, in execute
        return_value = super().execute(context)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 238, in execute
        return_value = self.execute_callable()
                       ^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 256, in execute_callable
        return runner.run(*self.op_args, **self.op_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/airflow/dags/test_smtp_notification.py", line 21, in failing_task
        raise RuntimeError("Error!")
    RuntimeError: Error!
    [2026-02-12, 07:59:28 UTC] {taskinstance.py:1242} INFO - Marking task as FAILED. dag_id=test_smtp_notification, task_id=failing_task, run_id=manual__2026-02-12T07:59:27.575809+00:00, execution_date=20260212T075927, start_date=20260212T075928, end_date=20260212T075928
    [2026-02-12, 07:59:28 UTC] {taskinstance.py:1580} INFO - Executing callback at index 0: SmtpNotifier
    [2026-02-12, 07:59:28 UTC] {base.py:84} INFO - Retrieving connection 'smtp_default'
    [2026-02-12, 07:59:28 UTC] {basenotifier.py:109} ERROR - Failed to send notification: 'NoneType' object has no attribute 'close'
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 282, in _run_raw_task
        TaskInstance._execute_task_with_callbacks(
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 3184, in _execute_task_with_callbacks
        result = self._execute_task(context, task_orig)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 3208, in _execute_task
        return _execute_task(self, context, task_orig)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 776, in _execute_task
        result = _execute_callable(context=context, **execute_callable_kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/taskinstance.py", line 742, in _execute_callable
        return ExecutionCallableRunner(
               ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/decorators/base.py", line 266, in execute
        return_value = super().execute(context)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/models/baseoperator.py", line 424, in wrapper
        return func(self, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 238, in execute
        return_value = self.execute_callable()
                       ^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/operators/python.py", line 256, in execute_callable
        return runner.run(*self.op_args, **self.op_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/operator_helpers.py", line 252, in run
        return self.func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/opt/airflow/dags/test_smtp_notification.py", line 21, in failing_task
        raise RuntimeError("Error!")
    RuntimeError: Error!
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 140, in notify
        smtp.send_email_smtp(
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 214, in send_email_smtp
        raise AirflowException("The 'smtp_client' should be initialized before!")
    airflow.exceptions.AirflowException: The 'smtp_client' should be initialized before!
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/notifications/basenotifier.py", line 107, in __call__
        self.notify(context)
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 139, in notify
        with self.hook as smtp:
             ^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 72, in __exit__
        self.smtp_client.close()
        ^^^^^^^^^^^^^^^^^^^^^^
    AttributeError: 'NoneType' object has no attribute 'close'

    I'm using the default Compose file with Airflow=2.11.0. If I remove the from_email (which is already given in the Web UI Connection tab), I get the error stated in the issue head:

    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/notifications/basenotifier.py", line 107, in __call__
        self.notify(context)
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/notifications/smtp.py", line 111, in notify
        if self.hook.from_email is not None:
           ^^^^^^^^^^^^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 365, in from_email
        return self.conn.extra_dejson.get("from_email")
               ^^^^^^^^^
      File "/home/airflow/.local/lib/python3.12/site-packages/airflow/providers/smtp/hooks/smtp.py", line 356, in conn
        raise AirflowException("The smtp connection should be loaded before!")
    airflow.exceptions.AirflowException: The smtp connection should be loaded before!

    What I have already done:

    • double checked the connection in the Web UI, checked that smtp-server (a Docker container with Mailpit) is reachable from within the worker and scheduler containers:
      (airflow)nc -zv smtp-server 1025
      Connection to smtp-server (172.18.0.3) 1025 port [tcp/*] succeeded!
    • checked that the connection is correctly retrieved by Airflow:
      from airflow.hooks.base import BaseHook
      
      conn = BaseHook.get_connection("smtp_default")
      print(conn.host, conn.port, conn.extra)  # Prints smtp-server 1025 {"from_email": "from_email", "timeout": 30, "retry_limit": 0, "disable_tls": true, "disable_ssl": true}
    • tried SmtpHook directly and with but again got airflow.exceptions.AirflowException: The 'smtp_client' should be initialized before!:
      def failure_callback(context):
          with SmtpHook(smtp_conn_id="smtp_default") as hook:
              hook.send_email_smtp(
                  to="to_email",
                  from_email="from_email",
                  subject="Test failure",
                  html_content="Body",
              )
      
      @dag(
          schedule=None,
          default_args={
              "on_failure_callback": [
                  failure_callback
              ]
          },
      )
      ...

    Thanks, reopened the issue. Feel free to investigate and contribute a fix if you want, otherwise it will wait for someone else to do that :)

  13. TopCoder2K commented on Feb 12, 2026

    @TopCoder2K
    Contributor

    Damn, I've found a bug: this loop inside the get_conn() method isn't entered when self.smtp_retry_limit == 0 (in the Web UI, I set "Number of Retries" to zero in order to better check connection problems). BUT! Here is another bug which added a headache to me: for some reason, the Web UI shows "Number of Retries" as 5 (instead of 0)! Since I forgot that I had set it to 0, I thought it was 5...

    In order to fix the first bug, it seems enough just to set the range() to start at 0 (since self.smtp_retry_limit is a number of retries = repeated tries after the first try). Should I open a PR, @shahar1?
    And I look forward to any thoughts regarding the second bug (I'm very bad at frontend).

    UPD:
    The bug with the Web UI is not reproduced in Airflow 3.1.7.

  14. shahar1 commented on Feb 12, 2026

    @shahar1
    Contributor

    Damn, I've found a bug: this loop inside the get_conn() method isn't entered when self.smtp_retry_limit == 0 (in the Web UI, I set "Number of Retries" to zero in order to better check connection problems). BUT! Here is another bug which added a headache to me: for some reason, the Web UI shows "Number of Retries" as 5 (instead of 0)! Since I forgot that I had set it to 0, I thought it was 5...

    In order to fix the first bug, it seems enough just to set the range() to start at 0 (since self.smtp_retry_limit is a number of retries = repeated tries after the first try). Should I open a PR, @shahar1?
    And I look forward to any thoughts regarding the second bug (I'm very bad at frontend).

    Please go ahead! It's better to continue the discussion on an open PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:providerskind:bugneeds-triageprovider:smtp

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions