Search code examples
amazon-web-servicesaws-lambdanodesaws-api-gateway

AWS Lambda function unable to send email


I have a simple AWS Lambda function that sends an email using nodemailer. The provider is 'Gmail' with:

  SMTP_SECURE: true,
  SMTP_PORT: 465

The problem is the API gateway URL times out after 30456.58 ms with 504 Gateway Timeout. It's clearly mentioned in AWS documentation that it will timeout after the 30s and that is acceptable too.

The same thing happens when I directly invoke lambda from the AWS lambda console. It times out too. The thing which is not making a sense to me it

transporter.sendMail(mailOptions);

why these lines take more than 30 seconds? and also when API gateway timeout lambda also timeout. I have already attached VPC, subnet, and security having traffic from all and also enable less secure on google.

Cloudwatch logs clearly indicate that my code is not going beyond:

const info = await transporter.sendMail(mailOptions);

PS: Everything works like a charm on my local machine, the problem is only in the cloud function.

here are the security outgoings:

Security group outbound rules:

security group

Lambda function outbound rules:

this is coming in lambda console


Solution

  • If an AWS Lambda function is connected to a VPC, it can only obtain Internet access if the VPC has a NAT Gateway or NAT Instance configured.

    This is because the Lambda function does not receive a public IP. Lambda functions should be configured to use private subnet(s), and then access the Internet via the NAT Gateway or NAT Instance.

    Lambda Destination

    If the Lambda function is invoked asynchronously, another option is to configure a Lambda Destination that triggers another Lambda function. This second Lambda function could be "outside" the VPC and connected to the Internet. The invocation is managed by the AWS service.

    So, the flow would be:

    Trigger --> Lambda 1 (does RDS stuff) --> Destination: Lambda 2 (does email stuff)
    

    The first Lambda function could pass information to the second Lambda function for inclusion in the email.

    API Gateway

    Another option is to keep the Lambda function "outside" the VPC, but have it call API Gateway to retrieve information from 'inside' the VPC.