2

Ok so this incredibly weird thing happened. I am running a python script to produce some output and store it in a file. At the end of the script, I am using subprocess module to send a mail via postfix. I run

subprocess.call(['sudo mail -s "Subject" person@example.com < /path/to/file.txt'], shell=True)

This executes but gives the message mail: Null message body; hope that's ok even though the file has contents. And I receive an email with no body (but correct subject).

When I run the command directly:

sudo mail -s "Subject" person@example.com < /path/to/file.txt

I receive the contents of the file in the email.

What is going wrong here? It has totally messed up my head!

Pravesh Jain
  • 4,128
  • 6
  • 28
  • 47
  • First, make sure you launch the Python script using sudo. Also, have you tried splitting the list you pass to subprocess.call? (['sudo', 'mail', '-s', "Subject", person@example.com, '<', '/path/to/file.txt''] – weirdev Jul 31 '15 at 18:10
  • I don't think running it as with sudo is going to help. You see I am still receiving the mail, just the body is missing. – Pravesh Jain Jul 31 '15 at 18:24
  • Piping the text file into `mail` on standard input would be somewhat safer, and would hopefully allow you to avoid `sudo` completely, as well as remove the need for `shell=True`. – tripleee Sep 21 '15 at 08:50

1 Answers1

0

As expected, it was an utterly stupid error (These are the best ones).

I wasn't flushing my file handle and sending the mail. So the message body was empty. Now I am using

file_name.flush()
file_name.close()
subprocess.call(['sudo mail -s "Subject" person@example.com < /path/to/file.txt'], shell=True)

and the mail I receive has the body. Phew!

Pravesh Jain
  • 4,128
  • 6
  • 28
  • 47
  • you could [pass input to the child process using `Popen.communicate()`](http://stackoverflow.com/q/163542/4279). Or just [send email using pure Python](http://stackoverflow.com/a/20787826/4279) – jfs Sep 21 '15 at 18:39