0

I'm trying to send text with multiple lines:

text = "This is a line 1
This is a line 2
This is a line 3"

in a python script with:

cmd = "echo {} | mail -s 'Test email' name@server.com".format(text)
os.system(cmd) 

but I get an error because new lines are interpreted as commands:

sh: line 1: This: command not found

printing it out, it result in:

echo This is line 1
This is line 2
This is line 3 | mail -s 'Test email' name@server.com

I think the solution is simple, but I did not find any useful solution.

Neuran
  • 137
  • 10

1 Answers1

2

The immediate problem is that strings in the shell need to be quoted if they contain newlines or etc. See When to wrap quotes around a shell variable.

But more fundamentally, you really don't want to use os.system here like this. Like its documentation already tells you, you generally want to prefer subprocess.

import subprocess

subprocess.run(
    ["mail", "-s", "Test email", "name@server.com"], 
    input=text, text=True, check=True)

or use smtplib to send email natively (or, conversely, don't use Python at all if all you need is a simple shell script, though you'd still need to fix the quoting then).

mail is poorly portable so if you haven't tested this on your system already, it might have additional problems. Perhaps see also How do I send a file as an email attachment using Linux command line?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • See also [Actual meaning of `shell=True` in subprocess](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) and perhaps https://stackoverflow.com/questions/4256107/running-bash-commands-in-python/51950538#51950538 – tripleee May 11 '22 at 15:24