简体   繁体   English

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

[英]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.我有一个线程 python 脚本,可以 ping 局域网上的 20 个节点,并打印出每个节点的状态:节点处于活动状态、节点处于关闭状态等。我希望将此输出发送到我的电子邮件帐户,因为我打算让这个脚本每周运行一次,它自己,如果我身体远离局域网,我不必担心,我可以查看我的电子邮件。

Language:PYTHON.语言:Python。 OS:Linux Mint 10 Julia.操作系统:Linux Mint 10 朱莉娅。 Thanks谢谢

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

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

Use smtplib .使用smtplib The example they provide is pretty good.他们提供的例子非常好。

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 True:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg += line

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

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

Take a look at the logging and logging.config, I've used this before to receive error messages from a script running in the background看一下 logging 和 logging.config,我之前使用过它来接收来自后台运行的脚本的错误消息

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

For example例如

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

And then the logging.conf然后是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')

From the above I would receive "THIS IS AN ERROR" in my email.从上面我会在我的电子邮件中收到“这是一个错误”。

Instead of having your main print the output, you could use a logger to print to stout and to the logger您可以使用logger打印到粗壮和logger ,而不是让您的主要print输出

You can set up a logger as follows according to the Logging Cookbook :您可以根据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现在用logger.info替换脚本中的print

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

A great resource on the topic of sending email with Python is Al Sweigart's 'Automate the Boring Stuff with Python'.关于使用 Python 发送电子邮件这一主题的一个很好的资源是 Al Sweigart 的“使用 Python 自动化无聊的东西”。 Chapter 18 is the part you want.第18章是你想要的部分。 In short, if you have an email address with one of the big email providers (think Google, Outlook, Yahoo, etc.) you can use their Simple Mail Transfer Protocol (SMTP) server(s) to handle your messages from Python.简而言之,如果您拥有大型电子邮件提供商之一(例如 Google、Outlook、Yahoo 等)的电子邮件地址,您可以使用他们的简单邮件传输协议 (SMTP) 服务器来处理来自 Python 的邮件。 As Al says:正如艾尔所说:

在此处输入图片说明

If you don't have an email address with one of the big providers or you're not in a position where you can use an email address from an outside provider, then it's a bit harder.如果您没有大型提供商之一的电子邮件地址,或者您无法使用外部提供商的电子邮件地址,那么这会有点困难。 Perhaps someone at your company can tell you 1) if your company has an SMTP server and 2) what its domain name and port number are.也许您公司的某个人可以告诉您 1) 您的公司是否有 SMTP 服务器以及 2) 它的域名和端口号是什么。

Once you have all that, sending out an email message from your program is a piece of cake:一旦你拥有了所有这些,从你的程序中发送一封电子邮件是小菜一碟:

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

Loggers are great too, so don't discount what everyone's said about them.记录器也很棒,所以不要低估每个人对它们的评价。 Print to the terminal.打印到终端。 Log to a file.登录到文件。 AND email out!并通过电子邮件发送! Loggers can do everything.记录器可以做任何事情。

You need a SMTP server to send Email.您需要一个 SMTP 服务器来发送电子邮件。 Check out the smtplib for Python查看 Python 的smtplib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM