-1

Python スクリプトを使用して、Amazon Workmail で自動化された E メールメッセージを送信できますか?

コードがハングし続け、実行できるときにSMTP サーバー接続エラーが発生します。どうすればこれを修正できますか? 私はそれがSMTP構成だと思いますが、それが何であるか知っている人はいますか?

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 <xxxxx@yyyyyy.co.uk>'
    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()
4

1 に答える 1