使用Amazon SES发送邮件,首先需要做如下两步准备工作:
- 注册AWS账户
- 验证邮箱地址或domain
下面分别是两种通过Amazon SES发送邮件的方式:使用SMTP,使用SWS SDK
使用SMTP
- 登录AWS控制台主页。进入控制台主页后,选择 Simple Email Service 进入
-
进入SES主页后,选择SMTP Settings进入,将看到如下界面:
该页面可以看到Server Name和Port的信息。
-
点击Create My SMTP Credentials, 进入下面的界面:
这一步会创建一个用于SMTP认证的IAM的用户,可以设置自己的IAM 用户名。然后点击Create
-
SMTP的安全凭证(用户名,密码)将会生成。该用户名,密码将在smtp login时使用。
安全凭证只在生成时可见和可下载,最好是记下或下载下来,并妥善保管
- Server Name, Port, SMTP用户名,密码都准备好了,现在可以通过Amazon SES SMTP Interface来发送邮件了。
下面是官网的Python例子(https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-smtp.html)
import smtplib
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Replace [email protected] with your "From" address.
# This address must be verified.
SENDER = '[email protected]'
SENDERNAME = 'Sender Name'
# Replace [email protected] with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = '[email protected]'
# Replace smtp_username with your Amazon SES SMTP user name.
USERNAME_SMTP = "smtp_username"
# Replace smtp_password with your Amazon SES SMTP password.
PASSWORD_SMTP = "smtp_password"
# (Optional) the name of a configuration set to use for this message.
# If you comment out this line, you also need to remove or comment out
# the "X-SES-CONFIGURATION-SET:" header below.
CONFIGURATION_SET = "ConfigSet"
# If you're using Amazon SES in an AWS Region other than US West (Oregon),
# replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
# endpoint in the appropriate region.
HOST = "email-smtp.us-west-2.amazonaws.com"
PORT = 587
# The subject line of the email.
SUBJECT = 'Amazon SES Test (Python smtplib)'
# The email body for recipients with non-HTML email clients.
BODY_TEXT = ("Amazon SES Test\r\n"
"This email was sent through the Amazon SES SMTP "
"Interface using the Python smtplib package."
)
# The HTML body of the email.
BODY_HTML = """
Amazon SES SMTP Email Test
This email was sent with Amazon SES using the
Python
smtplib library.
"""
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
msg['To'] = RECIPIENT
# Comment or delete the next line if you are not using a configuration set
msg.add_header('X-SES-CONFIGURATION-SET',CONFIGURATION_SET)
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(BODY_TEXT, 'plain')
part2 = MIMEText(BODY_HTML, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Try to send the message.
try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
#stmplib docs recommend calling ehlo() before & after starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, RECIPIENT, msg.as_string())
server.close()
# Display an error message if something goes wrong.
except Exception as e:
print ("Error: ", e)
else:
print ("Email sent!")
使用AWS SDK (for python)
- 安装 AWS SDK for python(Boto)
pip install boto3
- 获取AWS Access Key
要通过Amazon SES API来访问Amazon SES, 需要AWS Access Key(Access Key Id & Secret Access Key)。我们可以通过创建IAM用户来产生一个该IAM用户对应的Access Key。
-
从控制台主页进入IAM
-
进入“用户”, 然后点击“添加用户”
-
设置用户名,勾上编程访问, 然后点击“下一步:权限”
-
点击 直接附加现有策略
-
搜索 ses
-
选择 AmazonSESFullAccess, 然后点击下一步:审核
-
点击创建用户
用户创建成功,这里将会生成访问秘钥ID和私有访问秘钥。该秘钥对只有现在可以查看和下载,需要记下并妥善保管。
关闭该页面后就会在IAM 用户主页面看到刚刚创建成功的新用户。
-
点击进入可以看到该用户更多的详情
现在我们就获取了AWS该用户的credential,并且该用户拥有SES的访问权限。
- 创建credential file
创建下面的credential file. YOUR_AWS_ACCESS_KEY_ID,YOUR_AWS_SECRET_ACCESS_KEY就是刚刚获取的credential
[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
保存该文件到下面的路径:
If you're using... | Save the file as... |
---|---|
Windows | C:\Users |
Linux, macOS or Unix | ~/.aws/credentials |
注意不要带扩展文件名。
- 接下来就可以通过AWS SDK发送邮件了。
下面是AWS官网的例子(https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html)。
import boto3
from botocore.exceptions import ClientError
# Replace [email protected] with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Sender Name "
# Replace [email protected] with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = "[email protected]"
# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the
# ConfigurationSetName=CONFIGURATION_SET argument below.
CONFIGURATION_SET = "ConfigSet"
# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
AWS_REGION = "us-west-2"
# The subject line for the email.
SUBJECT = "Amazon SES Test (SDK for Python)"
# The email body for recipients with non-HTML email clients.
BODY_TEXT = ("Amazon SES Test (Python)\r\n"
"This email was sent with Amazon SES using the "
"AWS SDK for Python (Boto)."
)
# The HTML body of the email.
BODY_HTML = """
Amazon SES Test (SDK for Python)
This email was sent with
Amazon SES using the
AWS SDK for Python (Boto).
"""
# The character encoding for the email.
CHARSET = "UTF-8"
# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)
# Try to send the email.
try:
#Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
},
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
# If you are not using a configuration set, comment or delete the
# following line
ConfigurationSetName=CONFIGURATION_SET,
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
注意事项:
在使用SMTP方式创建SMTP安全凭证时,也会创建一个IAM用户。如下图所示:
- SMTP安全凭证
-
对应的IAM用户
但是SMTP安全凭证并不是IAM用户的Access Key. 所以不能将SMTP的安全凭证用作访问AWS SES API的credentials。
如果想用该IAM来访问SES SDK, 可以在该IAM下面重新创建一个访问秘钥(一个用户可以最多创建两个访问秘钥),用新生成的访问秘钥作为SES SDK Credential.
除了访问秘钥,SMTP 创建的IAM用户的访问权限是AmazonSesSendingAccess
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "*"
}
]
}
可以根据需要进行配置。