Bahlsen
Bahlsen

Reputation: 177

mailutils not working via subprocess.run in python

I am trying to send a mail via python's subprocess.run methode. Unfortunately, it is not working.

import subprocess

message = "Hello World"

process = subprocess.run(["mail", "-s", "Test, "[email protected]", "<<<", message], 
                     stdout=subprocess.PIPE, 
                     universal_newlines=True)

print (process.stdout)

I received the following Error:

mail: Cannot parse address <<<' (while expanding<<<'): Malformed email address

mail: Cannot parse address Hello World' (while expandingHello World'): Malformed email address

The command is working in the shell though (Linux Mint > 19.0).

Upvotes: 1

Views: 533

Answers (1)

Michael S
Michael S

Reputation: 880

The <<< syntax is a feature of bash. If you want to use that you need to run your command as an argument of the bash shell:

import subprocess
message = "Hello World"

command = "mail -s Test [email protected] <<< "+message
process = subprocess.run(
        ["bash","-c",command],
        stdout=subprocess.PIPE,
        universal_newlines=True)

print (process.stdout)

However, using shell expansion on dynamic content can be a security issue. A better way is, to use the input feature of subprocess.run ( python3 only )

import subprocess
message = "Hello World"

command = ["mail", "-s", "Test", "[email protected]"]
process = subprocess.run(
        command,
        input=message,
        stdout=subprocess.PIPE,
        universal_newlines=True)


print (process.stdout)

See also Python - How do I pass a string into subprocess.Popen (using the stdin argument)?

Upvotes: 1

Related Questions