How to send output from a python script to an email address

后端 未结 6 774
野性不改
野性不改 2021-02-05 22:38

I have a threaded python script that pings 20 nodes on a local area network, and prints out the status of each: Node is Alive, Node is Down, etc.. I would like to have this outp

6条回答
  •  暖寄归人
    2021-02-05 23:02

    Instead of having your main print the output, you could use a logger to print to stout and to the logger

    You can set up a logger as follows according to the Logging Cookbook:

    import logging
    log_file = r'C:\Users\user\Downloads\LogFileName.log'
    
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.INFO)
    
    # create file handler which logs even debug messages
    fh = logging.FileHandler('log_file')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)
    
    

    Now in replace print in your script with logger.info

    Example before:

    print("Printing status")
    

    Example after:

    logger.info("Printing status")
    

    Then you can email the log to yourself as follows:

    import smtplib
    from email.message import EmailMessage
    import os
    msg_body = "Body Text"
    
    msg = EmailMessage()
    
    msg['Subject'] = "Subject"
    msg['From'] = "send_from@email.com"
    msg['To'] = "send_to@email.com"
    
    msg.set_content(msg_body)
    
    if os.path.isfile(log_file):
            msg.add_attachment(open(log_file, "r").read(), filename=os.path.basename(log_file))
    
    
    # Send the message via our own SMTP server.
    s = smtplib.SMTP("smtpa.server")
    s.send_message(msg)
    s.quit()
    

提交回复
热议问题