如何通过mailx和subprocess发送邮件?

2024-05-14 03:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是EE,正在尝试编写一个脚本来使用Python简化文件检查

出于某种原因,我们的IT不允许我访问SMTP服务器,只允许通过mailx发送邮件。 因此,我考虑从Python运行mailx并发送它,就像它在我的控制台中工作一样。唉,这是一个例外。请参阅下面的Linux日志:

Python 3.1.1 (r311:74480, Dec  8 2009, 22:48:08) 
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> process=subprocess.Popen('echo "This is a test\nHave a loook see\n" | mailx -s "Test Python" mymail@mycomopany.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/depot/Python-3.1.1/lib/python3.1/subprocess.py", line 646, in __init__
    errread, errwrite)
  File "/depot/Python-3.1.1/lib/python3.1/subprocess.py", line 1146, in _execute_child
    raise child_exception

我是Python的新手(现在从Perl迁移)。有什么想法吗


Tags: 文件inpy脚本childlinuxlibline
3条回答

Lior Dagan的代码几乎是正确的/功能性的:这种方法中的错误是对subprocess.Popen的调用中缺少shell=True{}。任何实际考虑这种方法的人都应该知道subprocess文档警告:

Invoking the system shell with shell=True can be a security hazard if combined with untrusted input.

通常,应该首选F0RR和ghostdog74的解决方案,因为它们更健壮、更安全

您可以使用subprocess.call。比如:

subprocess.call(["mailx", "-s", "\"Test Python\"", "mymail@mycomopany.com"])

详情here

您可以使用smtplib

import smtplib
# email options
SERVER = "localhost"
FROM = "root@example.com"
TO = ["root"]
SUBJECT = "Alert!"
TEXT = "This message was sent with Python's smtplib."


message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

server = smtplib.SMTP(SERVER)
server.set_debuglevel(3)
server.sendmail(FROM, TO, message)
server.quit()

如果您真的想使用子流程(我建议不要使用)

import subprocess
import sys
cmd="""echo "test" | mailx -s 'test!' root"""
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
print errors,output

相关问题 更多 >