Reputation: 83697
I can send email by typing this command manually into the command line:
echo "test email" | mailx -s "test email" [email protected]
I get the email in my inbox, works.
It does not work with subprocess though:
import subprocess
recipients = ['[email protected]']
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?
Upvotes: 0
Views: 1423
Reputation: 148870
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" [email protected]
That is do not have the shell process the |
and pass it as a string to echo.
You have two ways to fix that :
echo
and mailx
) and pipe the output from echo
to the input of mailx
shell=True
parameter in subprocessThe second solution is simpler and would result in :
import subprocess
recipients = '[email protected]'
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)
Upvotes: 1