ClientError:调用SendEmail操作时发生错误(AccessDenied):

2024-09-26 22:53:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用lambda在文件到达s3存储桶的特定区域时自动发送电子邮件。当我将文件放在给定位置的bucket中并尝试运行时,我在cloudwatch日志中收到以下错误:

[ERROR] ClientError: An error occurred (AccessDenied) when calling the SendEmail operation: User `arn:aws:sts::123456789012:assumed-role/my-bot-role-abcdefg/my-bot' is not authorized to perform `ses:SendEmail' on resource `arn:aws:ses:eu-west-1:123456789012:identity/my_address@gmail.com'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 44, in lambda_handler
    Message = message   )
  File "/var/runtime/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 626, in _make_api_call
    raise error_class(parsed_response, operation_name)

我已将以下权限写入json策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": [
                "ses:SendEmail"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:ses:eu-west-1:123456789012:identity/*"
        }
    ]
}

在我计划为特定目的修改lambda句柄之前,我在lambda句柄中使用的代码的基础不是我自己的:

import json
import boto3

email_defaults = {
    "port" : 465,  # For SSL
    "smtp_server" : "smtp.gmail.com",
    "sender_email" : "my_sender_address@gmail.com", #replace as needed in testing
    "receiver_email" : "my_reciever_address@gmail.co.uk" #replace as needed in testing
    }

def lambda_handler(event, context):

    for i in event["Records"]:
        action = i["eventName"]
        ip = i["requestParameters"]["sourceIPAddress"]
        bucket_name = i["s3"]["bucket"]["name"]
        object = i["s3"]["object"]["key"]

    client = boto3.client("ses")

    subject = str(action) + 'Event from ' + bucket_name
    body = """
        <br>
        This email is to notify you regarding {} event.
        The object {} has been uploaded.
        Source IP: {}
    """.format(action, object, ip)

    message = {"Subject": {"Data": subject}, "Body": {"Html": {"Data": body}}}

    response = client.send_email(   Source = email_defaults["sender_email"], 
                                    Destination = {"ToAddresses": [email_defaults["receiver_email"]]}, 
                                    Message = message   )

    return "Hello world"

任何关于我可能忽略的事情的指导都将不胜感激,但我目前非常困惑


Tags: lambdanameinclientobjects3bucketemail
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:05

您必须添加允许向您的角色发送电子邮件的策略

在控制台中,转到IAM服务 IAM Service

然后,在左侧选择角色:

choose roles

选择您的角色: select role

然后添加内联策略 inline policy

choose SES as service, then all SES Actions, and all resources (you can reduce this permissions if needed)

然后检查并保存。完成了!你已经准备好通过lambda发送电子邮件了

相关问题 更多 >

    热门问题