0

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?

Richard Knop
  • 81,041
  • 149
  • 392
  • 552

1 Answers1

1

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 | 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
  • use shell=True parameter in subprocess

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)

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252