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

7 投票
3 回答
16752 浏览
提问于 2025-04-15 17:45

我是一名电子工程师,正在尝试用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转过来的)。有什么想法吗?

3 个回答

1

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的解决方案更好,因为它们更稳健也更安全。

1

你可以使用 subprocess.call。用法如下:

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

详细信息可以在 这里 找到

10

你可以使用 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()

如果你真的想用 subprocess(不过我不太建议这样做)。

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

撰写回答