跳至內容

如何使用 Amazon SES 作為 SMTP 主機從 Amazon MWAA DA​​ 任務傳送電子郵件?

2 分的閱讀內容
0

我想要使​​用 Amazon Simple Email Service (Amazon SES) 作為簡易郵件傳輸通訊協定 (SMTP) 主機,從 Amazon Managed Workflows for Apache Airflow (Amazon MWAA) 上的有向無環圖 (DAG) 任務傳送電子郵件。

解決方法

**注意:**如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤訊息,請參閱對 AWS CLI 錯誤進行疑難排解。此外,請確定您使用的是最新的 AWS CLI 版本

若要將 Amazon SES 作為 SMTP 主機,從 Amazon MWAA 上的 DAG 任務傳送電子郵件,請完成以下步驟:

  1. 設定使用 Amazon SES 傳送電子郵件
  2. 建立 Amazon SES SMTP 憑證,以便在 Amazon MWAA 中傳送電子郵件。
    **注意:**SMTP 介面憑證與您為 SMTP 使用者使用 AWS Identity and Access Management (IAM) 所建立的存取金鑰不同。
  3. 將 Apache Airflow 組態選項附加至 Amazon MWAA 環境。
  4. 為組態選項設定以下值:
    email.email_backend 設為 airflow.utils.email.send_email_smtp
    smtp.smtp_host 設為 email-smtp.region.amazonaws.com
    **注意:**將 region 替換為您的 AWS 區域。
    smtp.smtp_starttls 設為 True
    smtp.smtp_ssl 設為 False
    smtp.smtp_port 設為 587
    **注意:**使用連接埠 587 傳送 SMTP 流量。根據預設,AWS 會封鎖所有 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體從連接埠 25 傳出的 SMTP 流量。若要從連接埠 25 傳送傳出流量,請提交移除限制的請求
    smtp.smtp_mail_from 設為您的電子郵件地址。
    **注意:**如需上述組態選項的詳細資訊,請參閱 Apache Airflow 網站上的 [email][smtp]
  5. 為 SMTP 使用者和密碼分別建立一個 AWS Secrets Manager 密碼。使用步驟 2 中的 Amazon SES SMTP 憑證。然後,設定啟動指令碼以設定環境變數。
    **注意:**最佳實務是將 SMTP 憑證儲存在 Secrets Manager 中。
  6. 將以下 startup.sh 指令碼新增至您的 Amazon Simple Storage Service (Amazon S3) 儲存貯體:
    #!/bin/sh  
    # Get the SMTP username and password from secrets manager
    username=$(aws secretsmanager get-secret-value --secret-id airflow/variables/smtp.smtp_user --query SecretString --output text)
    password=$(aws secretsmanager get-secret-value --secret-id airflow/variables/smtp.smtp_password --query SecretString --output text)
    
    # Set the SMTP Environment variables with the username and password retrieved from Secrets Manager
    export AIRFLOW__SMTP__SMTP_USER=$username
    export AIRFLOW__SMTP__SMTP_PASSWORD=$password
    
    # Print the SMTP user
    echo "SMTP user is $AIRFLOW__SMTP__SMTP_USER"
    **注意:**您的 Amazon MWAA 執行角色必須具備擷取個別祕密值的權限
  7. 若要使用電子郵件組態選項和啟動指令碼的 Amazon S3 路徑更新 Amazon MWAA 環境,請執行以下 update-environment AWS CLI 命令:
    aws mwaa update-environment --name environment_name --startup-script-s3-path s3_path_for_startup_script
    **注意:**將 environment_name 替換為您的環境名稱,並將 s3_path_for_startup_script 替換為啟動指令碼的 S3 路徑。

當您建立或更新環境時,Apache Airflow 對成功、失敗和重試的回呼會使用前述組態。您也可以使用含有 EmailOperator 的任務來傳送電子郵件。如需更多資訊,請參閱 Apache Airflow 網站上的 airflow.providers.smtp.operators.smtp