Search code examples
pythonsmtplib

What is the best way to send python console output as email from within the script?


I have a python script that does multiple things and prints logs on the console. For now, I have not used any logging mechanism(I am just printing the required messages using print) How do I take all the prints and send it out as an email? Do I have to save it all in a variable and pass it to smtplib? or is there a better way?

Sample code

for job in fetch.getJobStats():
        if job['userName']+"_"+job['tenantId'] in summaryTotal:
            summary = summaryTotal[job['userName']+"_"+job['tenantId']]
        else:
            summary = Summary(job['userName'], job['tenantId'])
            summaryTotal[summary.user+"_"+summary.tenant] = summary

        summary.jobs.append(Job(job['jobId'], job['jobStatus'], int(job['fileSize'])))
        totalBw += int(job['fileSize'])

    print("Cumulative Size: " + str(totalBw))
    for summaryKey in summaryTotal.keys():
        summary = summaryTotal[summaryKey]

        inprogress = []
        failed = []
        completed = []
        cancelled = []
        totalBwTenantUser = 0

        for job in summary.jobs:
            totalBwTenantUser += job.filesize
            if job.status == "JOBCANCELLED":
                cancelled.append(job.id)
            elif job.status == "JOBCOMPLETED":
                completed.append(job.id)
            elif job.status == "INPROGRESS":
                completed.append(job.id)
            elif job.status == "JOBFAILED":
                completed.append(job.id)

        print("-" * 50)
        print("Tenant: " + summary.tenant)
        print("User  : " + summary.user)
        print("Size    : " + str(totalBwTenantUser))
        print("\n")
        print("INPROGRESS: " + str(inprogress))
        print("COMPLETED : " + str(completed))
        print("CANCELLED : " + str(cancelled))
        print("FAILED    : " + str(failed))
        print("-" * 50)

All the prints should be shot off an email.


Solution

  • You really should use the excellent logging system that comes with Python.

    Combine it with the mailinglogger handler and you have everything you need:

    import logging
    
    from mailinglogger.SummarisingLogger import SummarisingLogger
    
    handler = SummarisingLogger('from@example.com',
                                ('to@example.com',),
                                subject='[LOGS] %s (hostname)s',
                                mailhost='smtp.example.com')
    
    logging.basicConfig(format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p',
                        level=logging.INFO)
    logger = logging.getLogger()
    logger.addHandler(handler)
    
    logging.info('Sent by email.')