How to use AWS SES for mailing in Python

SES- Simple Email Service is a cloud service for mailing provided by AWS.

We can use the following Python script for mailing via AWS SES. Assuming that the sender email is already verified in SES.

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import boto3

client = boto3.client(
    'ses',
    region_name='REGION',
    aws_access_key_id='ACCES-KEY-ID,
    aws_secret_access_key='ACCESS-KEY'
)

message = MIMEMultipart()
message['Subject'] = 'SUBJECT'
message['From'] = 'SENDER'
message['To'] = ', '.join(['RECEIVER'])
part = MIMEText('BODY', 'html')
message.attach(part)# attachment
attachment_string=""
if attachment_string:   # if bytestring available
    part = MIMEApplication(str.encode('attachment_string'))
else:    # if file provided
    part = MIMEApplication(open('reports.csv', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename='reports.csv')
message.attach(part)
response = client.send_raw_email(
    Source=message['From'],
    Destinations=['RECEIVER'],
    RawMessage={
        'Data': message.as_string()
    }
)

Where REGION, ACCESS-KEY-ID, ACCESS-KEY, SENDER, RECEIVER and BODY need to be replaced with the required values.

Note that the user belongs to the key must have permissions over SES.

That's all…