Home > database >  Send email via mail command in python script
Send email via mail command in python script

Time:05-12

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.

CodePudding user response:

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?

  • Related