美文网首页python
通过 Amazon SES 发送邮件

通过 Amazon SES 发送邮件

作者: 狮子座圈圈 | 来源:发表于2018-09-28 17:00 被阅读0次

使用Amazon SES发送邮件,首先需要做如下两步准备工作:

  • 注册AWS账户
  • 验证邮箱地址或domain

下面分别是两种通过Amazon SES发送邮件的方式:使用SMTP,使用SWS SDK

使用SMTP

  1. 登录AWS控制台主页。进入控制台主页后,选择 Simple Email Service 进入
  2. 进入SES主页后,选择SMTP Settings进入,将看到如下界面:


    该页面可以看到Server Name和Port的信息。

  3. 点击Create My SMTP Credentials, 进入下面的界面:


    这一步会创建一个用于SMTP认证的IAM的用户,可以设置自己的IAM 用户名。然后点击Create

  4. SMTP的安全凭证(用户名,密码)将会生成。该用户名,密码将在smtp login时使用。
    安全凭证只在生成时可见和可下载,最好是记下或下载下来,并妥善保管


    3-copy.png
  5. 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 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 href='https://www.python.org/'>Python</a>
    <a href='https://docs.python.org/3/library/smtplib.html'>
    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)。我们可以通过创建IAM用户来产生一个该IAM用户对应的Access Key。
  • 从控制台主页进入IAM


  • 进入“用户”, 然后点击“添加用户”



  • 设置用户名,勾上编程访问, 然后点击“下一步:权限”


  • 点击 直接附加现有策略


  • 搜索 ses


  • 选择 AmazonSESFullAccess, 然后点击下一步:审核


  • 点击创建用户



    用户创建成功,这里将会生成访问秘钥ID和私有访问秘钥。该秘钥对只有现在可以查看和下载,需要记下并妥善保管。
    关闭该页面后就会在IAM 用户主页面看到刚刚创建成功的新用户。


  • 点击进入可以看到该用户更多的详情



    现在我们就获取了AWS该用户的credential,并且该用户拥有SES的访问权限。

  1. 创建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<yourUserName>.aws\credentials
Linux, macOS or Unix ~/.aws/credentials

注意不要带扩展文件名。

  1. 接下来就可以通过AWS SDK发送邮件了。
    下面是AWS官网的例子(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 href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
    <a href='https://aws.amazon.com/sdk-for-python/'>
      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'])

注意事项:

在使用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": "*"
        }
    ]
}

可以根据需要进行配置。

相关文章

  • 通过 Amazon SES 发送邮件

    使用Amazon SES发送邮件,首先需要做如下两步准备工作: 注册AWS账户 验证邮箱地址或domain 下面分...

  • 0328 - AWS 的大腿就是粗

    比如,Amazon 邮件服务 (Amazon SES),在绑定域名后,可以发给任意该域名下邮箱的邮件,比如 xxx...

  • 使用亚马逊的邮件服务(SES)发送邮件实战

    本篇文章记录了本人使用 AWS 的 SES 发送邮件的心得,以下的操作都是基于 AWS 提供的SES 服务的文档,...

  • SES 邮件发送反馈结果整理

    sentMessageCount 发送总数 deliveries 送达数(成功) bounces (邮件退回数) ...

  • SES介绍

    官方描述: Amazon Simple Email Service (Amazon SES) 是一款经济高效的仅出...

  • AWS SES 最佳实践

    http://media.amazonwebservices.com/AWS_Amazon_SES_Best_Pr...

  • 2018-10-11

    文本邮件的发送 1.邮件发送流程 ​ 邮件的发送是主动行为:主要通过 MUA/邮件客户端软件,将邮件内容发送给对应...

  • python自动发送邮件

    python自动发送邮件 在说python发送邮件之前,需要了解一下简单的邮件发送知识,邮件发送一般通过SMTP协...

  • QT使用SMTP实现发送简单中文文本邮件

    使用telnet发送邮件 通过使用cmd下的telnet发送一封邮件,掌握SMTP发送邮件的过程。 1. 准备工作...

  • Laravel 5.3 --通知

    1、简介 除了支持发送邮件之外,Laravel还支持通过多种传输通道发送通知,这些通道包括邮件、短信(通过Nexm...

网友评论

    本文标题:通过 Amazon SES 发送邮件

    本文链接:https://www.haomeiwen.com/subject/ltpuoftx.html