python代码实现Amazon SES 发送邮件

前言

遇到需求是使用python代码通过Amazon SES 发送邮件,在网上查询了半天,也解决了一些坑,现在把踩坑情况记录一下,方便后来人。

使用python代码通过Amazon SES发邮件之前,需要开通AWS账户,这个具体过程可以参考网上教程,有很多很详细博主已经写了,这里就不重复了,重点讲一下发邮件的代码和其中遇到的坑。

通过Amazon SES发邮件的方式也有两种,使用SMTP,使用SWS SDK,笔者这里用的是SWS SDK,因为这种方式比较简单,和国内腾讯云,阿里云使用的方式也比较相同。

报错和问题解决

发邮件的python代码,其实是基本上原封不动复制的官网的代码,但是,官网的代码会出现几个问题,先看代码吧

import boto3  #pip install boto3
from botocore.exceptions import ClientError

def send_email( ):

    # Replace [email protected] with your "From" address.
    # This address must be verified with Amazon SES.
    SENDER = "Sender Name <[email protected]>"

    # 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 = "ap-southeast-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"
    CN_S3_AKI = 'aws_access_key_id'   
    CN_S3_SAK = 'aws_secret_access_key'
    # Create a new SES resource and specify a region.
    client = boto3.client('ses',region_name=AWS_REGION, aws_access_key_id=CN_S3_AKI, aws_secret_access_key=CN_S3_SAK)

    # 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'])


if __name__ == "__main__":
	send_email( )

报错1:security token included in the request is invalid

这个主要是因为在使用boto3初始化client时候,官网代码是没有提示要添加aws_access_key_id和aws_secret_access_key,官方源码就是这样

	client = boto3.client('ses',region_name=AWS_REGION)
这是会报错的,需要添加公钥和私钥,错误才可以解决

报错2:Configuration set does not exist

这个报错主要是因为官方代码添加了CONFIGURATION_SET = “ConfigSet”,注掉这个设置,同时也要注掉 client.send_email里面的ConfigurationSetName=CONFIGURATION_SET就行了

报错3:Email address is not verified. The following identities failed the check in region AP-SOUTHEAST-2

这个就是使用的邮箱地址有问题,因为发邮件之前,aws会对发送和接收邮件地址都会做校验,看邮箱是否与区域相匹配

参考

使用 AWS 软件开发工具包通过 Amazon SES 发送电子邮件
通过 Amazon SES 发送邮件

猜你喜欢

转载自blog.csdn.net/weixin_42280271/article/details/129167713