要通过AWS SES发送带有附加文件的电子邮件,您可以使用AWS SDK或AWS CLI来实现。下面是使用AWS SDK(Python)的示例代码:
import boto3
def send_email_with_attachment():
# 创建SES客户端
ses_client = boto3.client('ses', region_name='us-west-2')
# 读取附加文件
with open('attachment.txt', 'rb') as file:
attachment_data = file.read()
# 将附加文件编码为Base64字符串
encoded_attachment = attachment_data.encode('base64')
# 发送电子邮件
response = ses_client.send_email(
Source='sender@example.com',
Destination={
'ToAddresses': ['recipient@example.com']
},
Message={
'Subject': {
'Data': 'Test email with attachment'
},
'Body': {
'Text': {
'Data': 'This is a test email with attachment'
}
}
},
# 在Message中指定附加文件
# 如果有多个附件,可以在Attachments列表中添加更多的字典
Attachments=[
{
'Filename': 'attachment.txt',
'Content': encoded_attachment,
'ContentType': 'text/plain'
}
]
)
print(response)
# 调用函数发送电子邮件
send_email_with_attachment()
在这个示例中,我们首先使用boto3.client
方法创建一个SES客户端。然后,我们读取要附加的文件,并使用Base64编码将其转换为字符串。最后,我们使用send_email
方法发送电子邮件,并在Attachments
参数中指定附加文件的详细信息(文件名、内容和内容类型)。
确保将代码中的region_name
、Source
、ToAddresses
和Filename
设置为适当的值,并将文件名改为您要附加的实际文件名。
请注意,发送带有附件的电子邮件需要您已经通过SES进行了验证的发送者电子邮件地址。
上一篇:AWS SES未收到邮件