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' [email protected]".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' [email protected]

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

1 Answer 1

3

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", "[email protected]"], 
    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?

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.