Search code examples
pythonfunctionvariablessmtplibconfigparser

Python smtplib and configparser as function


Hello I try to make a small monitoring, and in the monitoring.py, it should send a email with function sendmail.sende(). But i think, i got issues with variables. Could you give me some tips, what i do wrong please? This is the sendmail.py

def sende():
    import smtplib
    import configparser
    from email.message import Message

    config = configparser.ConfigParser()
    config.read('config.ini')
    absender=(config['SMTP']['absender'])
    password=(config['SMTP']['password'])
    empfaenger=(config['SMTP']['empfaenger'])
    smtphost=(config['SMTP']['smtphost'])
    port=int(config['SMTP']['port'])

    def readLastLog():
        log=open('log', 'r')
        for line in log:
            last= line
        print (last)
        log.close()

    #check for if variables is correct
    print("Email Config:")
    print(absender, '\n',empfaenger,'\n',smtphost,'\n',port)

    server = smtplib.SMTP_SSL(host=smtphost, port=port)

    #do I need realy need this?
    #server.esmtp_features['auth'] = 'LOGIN PLAIN'

    nachricht = Message()
    nachricht.set_payload(readLastLog())
    nachricht["Subject"] = "Kritische Warnung - Hardlimit erreicht"
    nachricht["FROM"] = absender
    nachricht["To"] = empfaenger

    server.login(absender, password)
    server.sendmail(absender, empfaenger, nachricht.as_string())
    server.quit()

sende()

Error:

Traceback (most recent call last):
  File "./sendmail.py", line 42, in <module>
    sende()
  File "./sendmail.py", line 38, in sende
    server.login(absender, password)
  File "/usr/lib/python3.5/smtplib.py", line 729, in login
    raise last_exception
  File "/usr/lib/python3.5/smtplib.py", line 720, in login
    initial_response_ok=initial_response_ok)
  File "/usr/lib/python3.5/smtplib.py", line 641, in auth
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Error: authentication failed: authentication failure')

Solution

  • You did not describe what is going wrong, so just guessing. But the function readLastLog is wrong:

    • it only print to stdout and does not return anything - so actually returns None
    • it is later used to initialize the payload which gives only nachricht.set_payload(None)

    Some other immediate improvements:

    • declaring a function inside another one is not wrong and have real use cases, but here I really wonder why readLastLog is defined inside sende body...
    • as you have built a Message with its To: and From: header, you could use the send_message function:

      ...
      server.send_message(nachricht)
      server.quit()