The EmailOperator
in Apache Airflow is used to send emails as part of your workflow. When using Gmail as the email service, you'll need to configure SMTP settings properly to ensure successful email delivery. Below are the steps to set up and use the EmailOperator
with Gmail in Airflow.
Step 1: Install Required Libraries
Make sure you have the required libraries installed. You may need to install the apache-airflow-providers-smtp
provider if it's not already installed:
Step 2: Configure Airflow to Use Gmail
You need to configure your Airflow instance to send emails using Gmail's SMTP server. This can be done in the airflow.cfg
configuration file or by setting environment variables.
Option A: Using airflow.cfg
- Locate the
airflow.cfg
file in your Airflow home directory (usually~/airflow/
). - Update the
[email]
section with your Gmail SMTP settings:
Option B: Using Environment Variables
Alternatively, you can set these values using environment variables:
Step 3: Create an App Password (Optional)
If you have two-factor authentication (2FA) enabled on your Google account, you will need to create an App Password to use with Airflow. Follow these steps:
- Go to your Google Account settings.
- Navigate to Security > Signing in to Google > App passwords.
- Create a new App Password for "Mail" and "Other" (you can name it "Airflow").
- Use this App Password in the
smtp_password
configuration.
Step 4: Use EmailOperator in a DAG
Now that you've configured your SMTP settings, you can use the EmailOperator
in your Airflow DAG.
Example DAG
Here's a simple example of how to use the EmailOperator
:
Explanation
- DAG Definition: The DAG is named
email_example_dag
and is scheduled to run daily. - Tasks:
start_task
: A dummy task representing the start of the DAG.send_email
: TheEmailOperator
sends an email to the specified recipient. You can customize the subject and the HTML content of the email.end_task
: Another dummy task representing the end of the DAG.
Notes
- HTML Content: The
html_content
parameter allows you to send HTML formatted emails. You can also use thetext_content
parameter for plain text emails. - Multiple Recipients: You can send emails to multiple recipients by providing a comma-separated string in the
to
parameter. - Testing: Make sure to test the email sending functionality by running your DAG manually and checking if the email is received.
This setup allows you to send emails from your Airflow workflows using Gmail effectively.
No comments:
Post a Comment