drdot
drdot

Reputation: 3347

python does not execute shell command "mail" properly

I use the following bash code to send email:

echo abc | mail -s Subject [email protected]

It works fine. Now I want to use the same command in python, so I write the following:

call(["echo abc" "|" "mail", "-s Subject", "[email protected]"], shell=True)

This python code does not send me the email and when I call the python script using

$python email.py

I get the following information from shell

No mail for rex

How does this happen?

Upvotes: 1

Views: 1919

Answers (2)

Ned Deily
Ned Deily

Reputation: 85035

Using subprocess.communicate as suggested elsewhere is a much better approach. You should avoid using shell=True for the reasons described here. But to answer your question why your call doesn't work, the problem is that you've broken the shell string up into rather arbitrary strings. If you pass the whole command as one string, it should work on Unix-y platforms at least.

call(["echo abc|mail -s Subject [email protected]"], shell=True)

See the details here. But such usage is not recommended.

Upvotes: 1

icktoofay
icktoofay

Reputation: 128991

There's no need for echo and piping between commands if you're using Python.
You can start a process and use the communicate method:

import subprocess

def send_message(recipient, subject, body):
    process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    process.communicate(body)

Upvotes: 2

Related Questions