简体   繁体   English

mailx不适用于子流程

[英]mailx does not work with subprocess

I can send email by typing this command manually into the command line: 我可以通过在命令行中手动输入以下命令来发送电子邮件:

 echo "test email" | mailx -s "test email" someone@somewhere.net

I get the email in my inbox, works. 我在收件箱中收到电子邮件,可以正常工作。

It does not work with subprocess though: 它不适用于子流程:

import subprocess
recipients = ['someone@somewhere.net']
args = [
    'echo', '"%s"' % 'test email', '|',
    'mailx',
    '-s', '"%s"' % 'test email',
] + recipients
LOG.info(' '.join(args))
subprocess.Popen(args=args, stdout=subprocess.PIPE).communicate()[0]

No errors, but I never receive the email in my inbox. 没有错误,但是我从未在收件箱中收到电子邮件。

Any ideas? 有任何想法吗?

The | | character has to be interpreted by the shell, not by the program. 字符必须由外壳而不是程序解释。 What you currently do looks like the following command : 您当前正在执行的操作类似于以下命令:

echo "test email" \| mailx -s "test email" someone@somewhere.net

That is do not have the shell process the | 那就是没有shell进程| and pass it as a string to echo. 并将其作为字符串传递回显。

You have two ways to fix that : 您有两种方法可以解决此问题:

  • explicitely start 2 commands from python with subprocess ( echo and mailx ) and pipe the output from echo to the input of mailx 明确地从python的子进程中启动2条命令( echomailx ),并将echo的输出通过管道传递到mailx的输入
  • use shell=True parameter in subprocess 在子流程中使用shell=True参数

The second solution is simpler and would result in : 第二种解决方案更简单,将导致:

import subprocess
recipients = 'someone@somewhere.net'
cmd = ('echo "%s" | mailx -s "%s"' % ('test email', 'test email')) + recipients
LOG.info(cmd)
subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]

But you should use full path in commands to avoid PATH environment problems that can result in security problems (you end in executing unwanted commands) 但是您应该在命令中使用完整路径,以避免可能导致安全性问题的PATH环境问题(最终导致执行不需要的命令)

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

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