在AWS SES发送电子邮件时,可以通过将附件转换为Base64字符串的方式添加附件。以下是一个使用Python和Boto3库的示例代码,演示如何在电子邮件中添加Base64编码的附件:
import boto3
import base64
def send_email_with_attachment():
# 创建SES客户端
client = boto3.client('ses', region_name='us-west-2')
# 打开并读取附件文件
with open('path/to/attachment.docx', 'rb') as file:
attachment_data = file.read()
# 对附件数据进行Base64编码
encoded_attachment = base64.b64encode(attachment_data).decode('utf-8')
# 构建电子邮件消息
message = {
'Subject': {
'Data': 'Test email with attachment'
},
'Body': {
'Text': {
'Data': 'This is a test email with attachment'
}
},
'Attachments': [
{
'ContentType': 'application/octet-stream',
'Data': encoded_attachment,
'Filename': 'attachment.docx'
}
]
}
# 发送电子邮件
response = client.send_email(
Source='sender@example.com',
Destination={
'ToAddresses': ['recipient@example.com']
},
Message=message
)
print(response)
# 调用发送邮件函数
send_email_with_attachment()
在上面的代码中,我们首先使用Boto3库创建了一个SES客户端。然后,我们打开并读取附件文件,然后使用base64.b64encode()
方法对附件数据进行Base64编码。接下来,我们构建了一个包含附件的电子邮件消息对象,其中Attachments
列表包含一个字典,其中包括附件的元数据,如内容类型、Base64编码的数据和文件名。
最后,我们使用client.send_email()
方法发送电子邮件,并打印出响应结果。请确保将sender@example.com
和recipient@example.com
替换为实际的发件人和收件人电子邮件地址,并将'path/to/attachment.docx'
替换为实际的附件文件路径。