如何将python脚本的输出发送到电子邮件地址

时间:2011-03-09 15:00:53

标签: python email scripting smtp

我有一个线程python脚本,在局域网上ping 20个节点,并打印出每个节点的状态:Node is Alive,Node is Down,等等。 我希望将此输出发送到我的电子邮件帐户,因为我打算让这个脚本每周运行一次,就可以自己运行,如果我离开局域网我不用担心,我可以只需查看我的电子邮件。

语言:PYTHON。操作系统:Linux Mint 10 Julia。感谢

6 个答案:

答案 0 :(得分:8)

如果它每周运行一次,你可能会从crontab运行它吗?

30 2 * * 5  python yourScript.py | mail -s outputFromScript your@email.address

答案 1 :(得分:6)

您可以使用print来打印粗壮和记录器,而不必使用主要的logger输出

您可以根据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)

现在将脚本中的print替换为logger.info

之前的示例:

print("Printing status")

以下示例:

logger.info("Printing status")

然后您可以通过以下方式将日志通过电子邮件发送给自己:

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()

答案 2 :(得分:5)

使用smtplib。他们提供的example非常好。

import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while 1:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print "Message length is " + repr(len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

答案 3 :(得分:2)

Al Sweigart的“使用Python自动处理无聊的东西”是有关使用Python发送电子邮件的重要资源。 Chapter 18是您想要的部分。简而言之,如果您拥有大型电子邮件提供商之一(例如Google,Outlook,Yahoo等)的电子邮件地址,则可以使用其简单邮件传输协议(SMTP)服务器来处理来自Python的消息。正如Al所说:

enter image description here

如果您没有大型供应商之一的电子邮件地址,或者您无法使用外部供应商的电子邮件地址,那么会有点困难。也许您公司的某人可以告诉您1)您的公司是否有SMTP服务器,以及2)其域名和端口号是什么。

一旦拥有了所有这些,从您的程序中发送一封电子邮件便是小菜一碟:

import smtplib

def main():

    # get message from node
    message1 = 'Node 1 is up :)'
    # print message from node
    print(message1)
    # get message from another node
    message2 = 'Node 2 is down :('
    # print that too
    print(message2)

    # now, all done talking to nodes.
    # time to compile node response results and send an email.

    # first, let's get every thing setup for the email
    from_me = 'awesome.name@my_email_provider.com'
    to_me = 'awesome.name@my_email_provider.com'
    email_message = message1 + '\n' + message2

    # second, let's make sure we have a connection to a Simple Mail Transfer Protocol (SMTP) server 
    # this server will receive and then send out our email message
    domain_name = 'smtp.my_email_provider.com'
    port_number = 587  # or maybe, 465
    server = smtplib.SMTP(domain_name, port_number)

    # alright! if that last line didn't raise an exceptions, then you're good to go. Send that bad boy off.
    server.sendmail(from_me, to_me, email_message)

if __name__ == '__main__':
    main()

记录器也很棒,所以不要轻视大家对它们的评价。 打印到终端。登录到文件。然后发电子邮件!记录仪可以做所有事情。

答案 4 :(得分:0)

您需要SMTP服务器才能发送电子邮件。查看smtplib for Python

答案 5 :(得分:0)

看一下logging和logging.config,之前我用过这个来从后台运行的脚本接收错误消息

http://docs.python.org/library/logging.html

例如

import logging
import logging.config

logDir = "./logs/"

logging.config.fileConfig(logDir+'logging.conf')
logger = logging.getLogger('email')

logger.debug('THIS IS A DEBUG MESSAGE')
logger.error('THIS IS AN ERROR')

然后是logging.conf

[loggers]
keys=root,email

[logger_root]
level=DEBUG
handlers=rotatingFileHandler

[logger_email]
level=ERROR
handlers=email
qualname=email

[formatters]
keys=emailFormatter,rotatingFormatter

[formatter_emailFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

[formatter_rotatingFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
datefmt=%m-%d %H:%M

[handlers]
keys=email,rotatingFileHandler

[handler_email]
class=handlers.SMTPHandler
level=ERROR
formatter=emailFormatter
args=('mail.xxx','x@x.com',['y@y.com',],'ERROR!',('x@x.com','xxx'))

[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=rotatingFormatter
args=('./logs/log.out', 'maxBytes=1000000', 'backupCount=5')

从上面我会在我的电子邮件中收到“这是一个错误”。