Search code examples
pythonsmtpamazon-workmail

Send email through AWS Workmail from Python script


Is it possible to send automated email messages with Amazon Workmail through a Python script?

My code keeps hanging and when I can the run I get a SMTP server connection error. How can I fix this? I presume, its the SMTP configuration, but does anyone know what that is?

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
import csv
from random import randint
from time import sleep


def send_email(email_recipient,
               email_subject,
               email_message,
               attachment_location=''):
    email_mime_sender = 'xxxxx <[email protected]>'
    email_sender = 'xxxxx'
    email_password = 'xxxxx'

    msg = MIMEMultipart()
    msg['From'] = email_mime_sender
    msg['To'] = email_recipient
    msg['Subject'] = email_subject

    msg.attach(MIMEText(email_message, 'plain'))

    if attachment_location != '':
      filename = os.path.basename(attachment_location)
      attachment = open(attachment_location, "rb")
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(attachment.read())
      encoders.encode_base64(part)
      part.add_header('Content-Disposition',
                      "attachment; filename= %s" % filename)
      msg.attach(part)

    try:
      server = smtplib.SMTP_SSL('smtp.mail.eu-west-1.awsapps.com', 465)
      server.ehlo()
      server.starttls()
      server.login(email_sender, email_password)
      text = msg.as_string()
      server.sendmail(email_sender, email_recipient, text)
      print('Email sent to %s' % email_recipient)
      server.quit()
    except:
      print("SMTP server connection error")
    return True


def main():
  file = 'test.csv'
  with open(file, "rb") as f:
    next(f)
    for line in f:
      line = line.replace("\n", "")
      line = line.replace("\r", "")
      split_line = line.split(",")
      email_subject = 'Can I ask you a few questions?'
      raw_email_message = [
          'Test',
          'Test'
      ]
      email_message = '\n\n'.join(raw_email_message)
      send_email(split_line[1], email_subject, email_message, '')
      sleep(randint(1, 3))


main()

Solution

  • Removing server.starttls() from the this block fixed it:

    try:
      server = smtplib.SMTP_SSL('smtp.mail.eu-west-1.awsapps.com', 465)
      server.ehlo()
      server.login(email_user, email_password)
      text = msg.as_string()
      server.sendmail(email_sender, email_recipient, text)
      print('Email sent to %s' % email_recipient)
      server.quit()
    except Exception as e:
      print(e)
      print("SMTP server connection error")
    return True