AWS SES (Amazon Simple Email Service) 是一种云端电子邮件服务,可用于发送和接收电子邮件。在使用 AWS SES 时,有两种方法可以发送电子邮件:SMTP 和 SES 客户端。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 配置 SMTP 服务器连接
smtp_server = 'email-smtp.us-west-2.amazonaws.com'
smtp_port = 587
smtp_username = 'your_smtp_username'
smtp_password = 'your_smtp_password'
# 创建邮件内容
msg = MIMEMultipart()
msg['Subject'] = '测试邮件'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
# 添加邮件正文
body = MIMEText('这是一封测试邮件。')
msg.attach(body)
# 添加附件(可选)
attachment = MIMEText('附件内容')
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.attach(attachment)
# 发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.send_message(msg)
import boto3
# 配置 AWS 访问密钥
aws_access_key_id = 'your_aws_access_key_id'
aws_secret_access_key = 'your_aws_secret_access_key'
aws_region = 'us-west-2'
# 创建 SES 客户端
client = boto3.client('ses', region_name=aws_region, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
# 创建邮件内容
subject = '测试邮件'
body_text = '这是一封测试邮件。'
sender = 'sender@example.com'
recipient = 'recipient@example.com'
# 发送邮件
response = client.send_email(
Destination={
'ToAddresses': [recipient],
},
Message={
'Body': {
'Text': {
'Charset': 'UTF-8',
'Data': body_text,
},
},
'Subject': {
'Charset': 'UTF-8',
'Data': subject,
},
},
Source=sender,
)
以上代码示例分别演示了如何使用 SMTP 和 SES 客户端发送电子邮件。在使用这两种方法之前,您需要先在 AWS 控制台上配置 SES,并获取相应的访问密钥。请根据您自己的配置信息进行调整。