AWS lambda 无法连接到 AWS 外部的 SMTP

AWS lambda is unable to connect to SMTP outside AWS

我正在使用 python 脚本通过 lambda 函数发送电子邮件。 lambda函数连接VPC,作为执行角色允许访问VPC。

部署函数并按下测试后,大约需要 8 分钟,然后 returns 出现以下错误:

{
      "errorMessage": "[Errno 97] Address family not supported by protocol",
      "errorType": "OSError",
      "requestId": "3d4a93d5-2ded-46e1-a480-9305d66d4ae5",
      "stackTrace": [
        "  File \"/var/task/lambda_function.py\", line 9, in lambda_handler\n    send_email()\n",
        "  File \"/var/task/lambda_function.py\", line 44, in send_email\n    mserver = smtplib.SMTP(SERVER, PORT)\n",
        "  File \"/var/lang/lib/python3.9/smtplib.py\", line 255, in __init__\n    (code, msg) = self.connect(host, port)\n",
        "  File \"/var/lang/lib/python3.9/smtplib.py\", line 341, in connect\n    self.sock = self._get_socket(host, port, self.timeout)\n",
        "  File \"/var/lang/lib/python3.9/smtplib.py\", line 312, in _get_socket\n    return socket.create_connection((host, port), timeout,\n",
        "  File \"/var/lang/lib/python3.9/socket.py\", line 843, in create_connection\n    raise err\n",
        "  File \"/var/lang/lib/python3.9/socket.py\", line 826, in create_connection\n    sock = socket(af, socktype, proto)\n",
        "  File \"/var/lang/lib/python3.9/socket.py\", line 232, in __init__\n    _socket.socket.__init__(self, family, type, proto, fileno)\n"
      ]
}

如果我 运行 这个脚本在 lambda 之外,它可以工作,但是当我在 lambda 函数中部署和测试时它 returns 这个错误。

还有其他人遇到过这个问题吗?

参见KB article:如何从我的 Amazon EC2 实例或 AWS Lambda 函数中删除端口 25 的限制?

AWS blocks outbound traffic on port 25 (SMTP) of all EC2 instances and Lambda functions by default. If you want to send outbound traffic on port 25, you can request for this restriction to be removed.

或者,考虑使用简单电子邮件服务 (SES)。参见 How do I send email using Lambda and Amazon SES?