python smtplib error handling code example

python smtplib error handling

1

1 Example

0
def runClient(configName = 'default', testFile = './test.xml'):
  cliCfg = getClientConfig(configName)
  print cliCfg.find('logfile').text
  # startLogger(cliCfg.find('logfile').text)
  clientCert = cliCfg.find('cert').text
  clientKey = cliCfg.find('key').text
  serverHost = cliCfg.find('serverhost').text
  serverPort = int(cliCfg.find('serverport').text)

  myMail = MailMessageHandler()
  msgSrc = myMail.readMessageSource(testFile)
  allMsgs = myMail.processMessages(msgSrc)
  inx = 1
  for msg in allMsgs:
    validMsg = True
    requiredKeys = ('ehlo', 'sndr', 'rcpt', 'body')
    for msgItems in requiredKeys:
      if len(msg[msgItems]) == 0:
        validMsg = False
    if validMsg:
      try:
        server = None
        server = smtplib.SMTP(serverHost, serverPort)
        server.ehlo(msg['ehlo'])
        thisSender = msg['sndr']
        thisRecipient = msg['rcpt']
        thisMessage = MIMEText(msg['body'])
        thisMessage['To'] = email.utils.formataddr(('', thisRecipient))
        thisMessage['From'] = email.utils.formataddr(('', thisSender))
        thisMessage['Subject'] = msg['subject']
        thisMessage['Message-id'] = email.utils.make_msgid()
        now = datetime.now()
        day = now.strftime('%a')
        date = now.strftime('%d %b %Y %X')
        thisMessage['Date'] = day + ', ' + date + ' -0000'
        if msg['tls'].lower() == 'true':
          server.starttls('certs/client/client.key', 'certs/client/client.crt')
          logging.info ("Message: " + thisMessage['Message-id'] + " to be sent over TLS")
        server.sendmail(thisSender, thisRecipient.split(","), thisMessage.as_string())
        logging.info ("Message: " + thisMessage['Message-id'] + " sent successfully to " + serverHost + ":" + cliCfg.find('serverport').text)
        logging.info ("Message: " + thisMessage['Message-id'] + " had sender: " + thisMessage['From'])
        logging.info ("Message: " + thisMessage['Message-id'] + " had recipient(s): " + thisMessage['To'])
      except socket.error as e:
        logging.error ("Could not connect to " + serverHost + ":" + cliCfg.find('serverport').text + " - is it listening / up?")
      except:
        print "Unknown error:", sys.exc_info()[0]
      finally:
        if server != None:
          server.quit()
    else:
      print "Improperly formatted source mail - please check"

Other Code Examples