要解决Amazon SES重复发送电子邮件的问题,可以通过在代码中添加一些逻辑来避免重复发送。
以下是一个示例代码,演示了如何使用Amazon SES发送电子邮件,并避免重复发送:
import boto3
# 创建SES客户端
client = boto3.client('ses', region_name='us-west-2')
# 检查是否已经发送过相同的电子邮件
def check_duplicate_email(email):
# 这里可以根据具体需求,选择一个适合的方式来检查重复
# 可以使用数据库、缓存或其他媒介来存储已发送的电子邮件
# 这里只是简单地使用一个列表来存储已发送的电子邮件
sent_emails = ["example1@example.com", "example2@example.com"]
if email in sent_emails:
return True
else:
sent_emails.append(email)
return False
# 发送电子邮件
def send_email(email, subject, message):
if not check_duplicate_email(email):
response = client.send_email(
Destination={
'ToAddresses': [
email,
],
},
Message={
'Body': {
'Text': {
'Charset': 'UTF-8',
'Data': message,
},
},
'Subject': {
'Charset': 'UTF-8',
'Data': subject,
},
},
Source='noreply@example.com',
)
print("Email sent!")
else:
print("Email already sent!")
# 示例用法
send_email("example1@example.com", "Hello", "This is a test email.")
send_email("example2@example.com", "Hello", "This is another test email.")
send_email("example1@example.com", "Hello", "This email should not be sent again.")
在这个示例中,使用check_duplicate_email函数来检查电子邮件是否已经发送过。如果已经发送过,则send_email函数不会调用Amazon SES发送电子邮件,而是输出一条消息表示电子邮件已经发送过了。
可以根据具体需求自定义check_duplicate_email函数的实现方式,例如使用数据库来存储发送记录,或者使用缓存来提高性能。这个示例只是一个简单的演示,并不涵盖所有的实现方式。