Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 output sent to my email account, Because I intend to make this script to run once a week, on it's own, And if i'm physically away from the lan I won't have to worry, I can just check my email.

Language:PYTHON. OS:Linux Mint 10 Julia. Thanks

like image 860
Samuel Avatar asked Mar 09 '11 15:03

Samuel


2 Answers

If it runs once a week, you will probably run it from crontab?

30 2 * * 5  python yourScript.py | mail -s outputFromScript [email protected]
like image 172
eumiro Avatar answered Oct 01 '22 02:10

eumiro


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'] = "[email protected]"
msg['To'] = "[email protected]"

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()
like image 28
C. Fennell Avatar answered Oct 01 '22 03:10

C. Fennell