Berk
Berk

Reputation: 263

smtplib with AWS SES could not send emails with attachments

I use AWS SES to send emails from my instance - it works when I send just messages, but when files are attached to emails, it could not send and just gets pending.

It works when I do it from a local system, but from AWS. I'm wondering what happens when a file is attached to an email - is there somethings in AWS blocking it - or I need to use something different from smptlib of email?

I use the script below:

subject = 'xx'
body = "xx"
sender_email = "[email protected]" `#this email address is confirmed in aws`
user = "xxxxx"  #ses username  

receiver_email = '[email protected]' `#this email address is confirmed in aws`
password = 'xxxxx' # ses password   

message = MIMEMultipart()
message["From"] = formataddr(('name', '[email protected]'))
message["To"] = receiver_email
message["Subject"] = subject    
# Add attachment to message and convert message to string
message.attach(MIMEText(body, "plain"))    
filename =  'sdf.txt' #the file that will be sent.    
   
with open(filename, "rb") as attachment:
    ## Add file as application/octet-stream
    # Email client can usually download this automatically as attachment

    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email   
encoders.encode_base64(part)   
   
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)    

message.attach(part)
text = message.as_string()    
   
# Log in to server using secure context and send email
context = ssl.create_default_context()
try:
    with smtplib.SMTP_SSL("email-smtp.us-east-1.amazonaws.com", 465, context=context  ) as server:
        server.login(user, password)
        server.sendmail(sender_email, receiver_email, text)
        server.close()
except smtplib.SMTPException as e:
        print("Error: ", e)    

Upvotes: 0

Views: 1918

Answers (1)

Berk
Berk

Reputation: 263

I modified the script, below - now it works nicely either with/without attachments in aws.

msg = MIMEMultipart()
body_part = MIMEText('xxxx', 'plain')
msg['Subject'] = 'xxx'
msg['From'] = formataddr(('xxxx', '[email protected]'))
msg['To'] = '[email protected]'
# Add body to email
msg.attach(body_part)
# open and read the file in binary
with open(path ,'rb') as file:
# Attach the file with filename to the email
    msg.attach(MIMEApplication(file.read(), Name='xxx'))
# Create SMTP object
smtp_obj = smtplib.SMTP_SSL("email-smtp.us-east-1.amazonaws.com", 465)
# Login to the server
user = "xxx"
# Replace smtp_password with your Amazon SES SMTP password.
password = 'xxx'
smtp_obj.login(user, password)
# Convert the message to a string and send it
smtp_obj.sendmail(msg['From'], msg['To'], msg.as_string())
smtp_obj.quit()

Upvotes: 1

Related Questions