通過 Amazon SES 發(fā)送郵件

使用Amazon SES發(fā)送郵件,首先需要做如下兩步準(zhǔn)備工作:

  • 注冊AWS賬戶
  • 驗(yàn)證郵箱地址或domain

下面分別是兩種通過Amazon SES發(fā)送郵件的方式:使用SMTP,使用SWS SDK

使用SMTP

  1. 登錄AWS控制臺主頁。進(jìn)入控制臺主頁后,選擇 Simple Email Service 進(jìn)入
  2. 進(jìn)入SES主頁后,選擇SMTP Settings進(jìn)入,將看到如下界面:


    該頁面可以看到Server Name和Port的信息。

  3. 點(diǎn)擊Create My SMTP Credentials, 進(jìn)入下面的界面:


    這一步會創(chuàng)建一個用于SMTP認(rèn)證的IAM的用戶,可以設(shè)置自己的IAM 用戶名。然后點(diǎn)擊Create

  4. SMTP的安全憑證(用戶名,密碼)將會生成。該用戶名,密碼將在smtp login時使用。
    安全憑證只在生成時可見和可下載,最好是記下或下載下來,并妥善保管


    3-copy.png
  5. Server Name, Port, SMTP用戶名,密碼都準(zhǔn)備好了,現(xiàn)在可以通過Amazon SES SMTP Interface來發(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)

  1. 安裝 AWS SDK for python(Boto)

pip install boto3

  1. 獲取AWS Access Key
    要通過Amazon SES API來訪問Amazon SES, 需要AWS Access Key(Access Key Id & Secret Access Key)。我們可以通過創(chuàng)建IAM用戶來產(chǎn)生一個該IAM用戶對應(yīng)的Access Key。
  • 從控制臺主頁進(jìn)入IAM


  • 進(jìn)入“用戶”, 然后點(diǎn)擊“添加用戶”



  • 設(shè)置用戶名,勾上編程訪問, 然后點(diǎn)擊“下一步:權(quán)限”


  • 點(diǎn)擊 直接附加現(xiàn)有策略


  • 搜索 ses


  • 選擇 AmazonSESFullAccess, 然后點(diǎn)擊下一步:審核


  • 點(diǎn)擊創(chuàng)建用戶



    用戶創(chuàng)建成功,這里將會生成訪問秘鑰ID和私有訪問秘鑰。該秘鑰對只有現(xiàn)在可以查看和下載,需要記下并妥善保管。
    關(guān)閉該頁面后就會在IAM 用戶主頁面看到剛剛創(chuàng)建成功的新用戶。


  • 點(diǎn)擊進(jìn)入可以看到該用戶更多的詳情



    現(xiàn)在我們就獲取了AWS該用戶的credential,并且該用戶擁有SES的訪問權(quán)限。

  1. 創(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ò)展文件名。

  1. 接下來就可以通過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安全憑證時,也會創(chuàng)建一個IAM用戶。如下圖所示:

  • SMTP安全憑證
  • 對應(yīng)的IAM用戶



    但是SMTP安全憑證并不是IAM用戶的Access Key. 所以不能將SMTP的安全憑證用作訪問AWS SES API的credentials。
    如果想用該IAM來訪問SES SDK, 可以在該IAM下面重新創(chuàng)建一個訪問秘鑰(一個用戶可以最多創(chuàng)建兩個訪問秘鑰),用新生成的訪問秘鑰作為SES SDK Credential.
    除了訪問秘鑰,SMTP 創(chuàng)建的IAM用戶的訪問權(quán)限是AmazonSesSendingAccess

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ses:SendRawEmail",
            "Resource": "*"
        }
    ]
}

可以根據(jù)需要進(jìn)行配置。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容