Home > Software design >  AWS lambda is unable to connect to SMTP outside AWS
AWS lambda is unable to connect to SMTP outside AWS

Time:09-23

I am using a python script to send an e-mail through a lambda function. The lambda function is connected to a VPC and as the execution role to allow the access to the VPC.

After deploying the function and pressing test it takes around 8 minutes and then returns the following error:

{
      "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"
      ]
}

If I run this script outside the lambda, it works, but when I deploy and test in the lambda function it returns this error.

Has anyone else had this issue?

CodePudding user response:

See KB article: How do I remove the restriction on port 25 from my Amazon EC2 instance or AWS Lambda function?

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.

Alternatively, consider using Simple Email Service (SES). See How do I send email using Lambda and Amazon SES?

  • Related