使用Amazon SES發(fā)送郵件蛤迎,首先需要做如下兩步準(zhǔn)備工作:
- 注冊(cè)AWS賬戶
- 驗(yàn)證郵箱地址或domain
下面分別是兩種通過(guò)Amazon SES發(fā)送郵件的方式:使用SMTP,使用SWS SDK
使用SMTP
- 登錄AWS控制臺(tái)主頁(yè)废登。進(jìn)入控制臺(tái)主頁(yè)后,選擇 Simple Email Service 進(jìn)入
-
進(jìn)入SES主頁(yè)后舀患,選擇SMTP Settings進(jìn)入滴劲,將看到如下界面:
該頁(yè)面可以看到Server Name和Port的信息底扳。
-
點(diǎn)擊Create My SMTP Credentials, 進(jìn)入下面的界面:
這一步會(huì)創(chuàng)建一個(gè)用于SMTP認(rèn)證的IAM的用戶,可以設(shè)置自己的IAM 用戶名遏暴。然后點(diǎn)擊Create
-
SMTP的安全憑證(用戶名侄刽,密碼)將會(huì)生成。該用戶名朋凉,密碼將在smtp login時(shí)使用州丹。
安全憑證只在生成時(shí)可見(jiàn)和可下載,最好是記下或下載下來(lái)杂彭,并妥善保管
3-copy.png - Server Name, Port, SMTP用戶名墓毒,密碼都準(zhǔn)備好了,現(xiàn)在可以通過(guò)Amazon SES SMTP Interface來(lái)發(fā)送郵件了亲怠。
下面是官網(wǎng)的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 sender@example.com with your "From" address.
# This address must be verified.
SENDER = 'sender@example.com'
SENDERNAME = 'Sender Name'
# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = 'recipient@example.com'
# 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 = """<html>
<head></head>
<body>
<h1>Amazon SES SMTP Email Test</h1>
<p>This email was sent with Amazon SES using the
<a >Python</a>
<a >
smtplib</a> library.</p>
</body>
</html>
"""
# 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
要通過(guò)Amazon SES API來(lái)訪問(wèn)Amazon SES所计, 需要AWS Access Key(Access Key Id & Secret Access Key)。我們可以通過(guò)創(chuàng)建IAM用戶來(lái)產(chǎn)生一個(gè)該IAM用戶對(duì)應(yīng)的Access Key团秽。
-
從控制臺(tái)主頁(yè)進(jìn)入IAM
-
進(jìn)入“用戶”主胧, 然后點(diǎn)擊“添加用戶”
-
設(shè)置用戶名,勾上編程訪問(wèn)习勤, 然后點(diǎn)擊“下一步:權(quán)限”
-
點(diǎn)擊 直接附加現(xiàn)有策略
-
搜索 ses
-
選擇 AmazonSESFullAccess, 然后點(diǎn)擊下一步:審核
-
點(diǎn)擊創(chuàng)建用戶
用戶創(chuàng)建成功踪栋,這里將會(huì)生成訪問(wèn)秘鑰ID和私有訪問(wèn)秘鑰。該秘鑰對(duì)只有現(xiàn)在可以查看和下載图毕,需要記下并妥善保管夷都。
關(guān)閉該頁(yè)面后就會(huì)在IAM 用戶主頁(yè)面看到剛剛創(chuàng)建成功的新用戶。
-
點(diǎn)擊進(jìn)入可以看到該用戶更多的詳情
現(xiàn)在我們就獲取了AWS該用戶的credential,并且該用戶擁有SES的訪問(wèn)權(quán)限吴旋。
- 創(chuàng)建credential file
創(chuàng)建下面的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<yourUserName>.aws\credentials |
Linux, macOS or Unix | ~/.aws/credentials |
注意不要帶擴(kuò)展文件名损肛。
- 接下來(lái)就可以通過(guò)AWS SDK發(fā)送郵件了。
下面是AWS官網(wǎng)的例子(https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html)荣瑟。
import boto3
from botocore.exceptions import ClientError
# Replace sender@example.com with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Sender Name <sender@example.com>"
# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = "recipient@example.com"
# 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 = """<html>
<head></head>
<body>
<h1>Amazon SES Test (SDK for Python)</h1>
<p>This email was sent with
<a >Amazon SES</a> using the
<a >
AWS SDK for Python (Boto)</a>.</p>
</body>
</html>
"""
# 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'])
注意事項(xiàng):
在使用SMTP方式創(chuàng)建SMTP安全憑證時(shí),也會(huì)創(chuàng)建一個(gè)IAM用戶摩泪。如下圖所示:
-
SMTP安全憑證
-
對(duì)應(yīng)的IAM用戶
但是SMTP安全憑證并不是IAM用戶的Access Key. 所以不能將SMTP的安全憑證用作訪問(wèn)AWS SES API的credentials笆焰。
如果想用該IAM來(lái)訪問(wèn)SES SDK, 可以在該IAM下面重新創(chuàng)建一個(gè)訪問(wèn)秘鑰(一個(gè)用戶可以最多創(chuàng)建兩個(gè)訪問(wèn)秘鑰),用新生成的訪問(wèn)秘鑰作為SES SDK Credential.
除了訪問(wèn)秘鑰见坑,SMTP 創(chuàng)建的IAM用戶的訪問(wèn)權(quán)限是AmazonSesSendingAccess
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "*"
}
]
}
可以根據(jù)需要進(jìn)行配置嚷掠。