当前位置: 代码迷 >> python >> 如何将python脚本的输出发送到电子邮件地址
  详细解决方案

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

热度:50   发布时间:2023-06-27 21:18:34.0

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

语言:Python。 操作系统:Linux Mint 10 朱莉娅。 谢谢

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

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

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

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

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

例如

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

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

您可以使用logger打印到粗壮和logger ,而不是让您的主要print输出

您可以根据如下设置记录器:

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)

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

之前的例子:

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

关于使用 Python 发送电子邮件这一主题的一个很好的资源是 Al Sweigart 的“使用 Python 自动化无聊的东西”。 是你想要的部分。 简而言之,如果您拥有大型电子邮件提供商之一(例如 Google、Outlook、Yahoo 等)的电子邮件地址,您可以使用他们的简单邮件传输协议 (SMTP) 服务器来处理来自 Python 的邮件。 正如艾尔所说:

如果您没有大型提供商之一的电子邮件地址,或者您无法使用外部提供商的电子邮件地址,那么这会有点困难。 也许您公司的某个人可以告诉您 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()

记录器也很棒,所以不要低估每个人对它们的评价。 打印到终端。 登录到文件。 并通过电子邮件发送! 记录器可以做任何事情。

您需要一个 SMTP 服务器来发送电子邮件。 查看 Python 的