如何使用 Amazon SES 作为 SMTP 主机来通过 Amazon MWAA DAG 任务发送电子邮件?

2 分钟阅读
0

我想使用 Amazon Simple Email Service (Amazon SES) 作为 Simple Mail Transfer Protocol (SMTP) 主机,来通过 Amazon Managed Workflows for Apache Airflow (Amazon MWAA)上的 Directed Acyclic Graph (DAG) 任务发送电子邮件。

解决方案

**注意:**如果您在运行 AWS 命令行界面 (AWS CLI) 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI

要使用 Amazon SES 作为 SMTP 主机,通过 Amazon MWAA 上的 DAG 任务发送电子邮件,请完成以下步骤:

  1. 使用 Amazon SES 设置电子邮件发送
  2. 创建 Amazon SES SMTP 凭证以在 Amazon MWAA 中发送电子邮件。
    **注意:**SMTP 接口凭证不同于您使用 AWS Identity Access and Management (IAM) 为 SMTP 用户创建的访问密钥。
  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 设置为 False
    smtp.smtp_ssl 设置为 True
    smtp.smtp_port 设置为 587
    **注意:**请使用端口 587 处理 SMTP 流量。默认情况下,AWS 会阻止来自所有 Amazon Elastic Compute Cloud (Amazon EC2) 实例的出站 SMTP 流量通过端口 25。要通过端口 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. 运行 update-environment 命令,使用电子邮件配置选项和启动脚本的 Amazon S3 路径更新 Amazon MWAA 环境。

**注意:**创建或更新环境时,Apache Airflow 成功、失败和重试的回调会使用前面的配置。您还可以使用具有 EmailOperator 的任务来发送电子邮件。有关更多信息,请参阅 Apache Airflow 网站上的 airflow.operators.email