Send an email through Amazon SES programmatically from Python

Before you begin, perform the following tasks:

Verify your email address with Amazon SES—Before you can send an email with Amazon SES, you must verify that you own the sender’s email address. If your account is still in the Amazon SES sandbox, you must also verify the recipient email address. The easiest way to verify email addresses is by using the Amazon SES console. 

For more information, see Verifying email addresses in Amazon SES

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses.html

Get your AWS credentials—You need an AWS access key ID and AWS secret access key to access Amazon SES using an SDK. You can find your credentials by using the Security Credentials page of the AWS Management Console. 

For more information about credentials, see Types of Amazon SES credentials

https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-concepts-credentials.html

Use the below code for sending email from python code,

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
 
class sendemail:
    @staticmethod
    def send_email(toemail, message):
       try:
        msg = MIMEMultipart()
        msg['Subject'] = "Message Subject"
        msg.attach(MIMEText(message))
        fromaddr = 'abc@gmail.com' #verified email address which is added on aws
        toaddrs  = toemail
        smtp_server = 'email-smtp.ap-south-1.amazonaws.com' #aws smtp server
        smtp_username = 'fsfsfsfsfgfdfdgtrtyryry' #smtp credential
        smtp_password = 'sdfsfsdfrfhsjdfhsjfhsjfhsjfhsjfh' #smtp credential
        smtp_port = '587'
        smtp_do_tls = True
         
        server = smtplib.SMTP(
            host = smtp_server,
            port = smtp_port,
            timeout = 10
        )
        server.set_debuglevel(10)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(smtp_username, smtp_password)
        server.sendmail(fromaddr, toaddrs, msg.as_string())
         return "ok"
       except:
        return "failed"

Leave a Reply

Your email address will not be published. Required fields are marked *